
我正在開發一個腳本,它執行需要包含在已填充的文字檔案中的計算。文件行的格式為:
1 20/10/16 12:00 take car in the garage joe's garage
在腳本中,我從計算中得到一個數字,該數字將替換該行的第一個數字。例如,「計算」會傳回值 15,那麼腳本必須存取有問題的檔案並更改有問題的行應如下所示:
15 20/10/16 12:00 take car in the garage joe's garage
關鍵是我不知道如何完成這個改變。它可以位於 bash、awk、sed 或任何可用資源中。謝謝。
答案1
怎麼樣:
awk -v old=$oldNum -v new=$newNum \
'{if ($1==old) {$1=new; print} else {print}}' input.txt > output.txt
像這樣嘗試過:
$ cat input.txt
2 19/10/16 15:30 some other line
1 20/10/16 12:00 take car in the garage joe's garage
3 17/10/16 5:30 another one
$ oldNum=2
$ newNum=15
運行 awk 命令,然後:
$ cat output.txt
15 19/10/16 15:30 some other line
1 20/10/16 12:00 take car in the garage joe's garage
3 17/10/16 5:30 another one
這是你想要的嗎?如果您希望結果出現在原始文件中,則只需mv
具有新名稱的輸出文件input.txt
,該文件應該覆蓋輸入文件(使用反斜線\mv
以避免命令別名mv
)。
注意:您可能可以使用較短的 awk 指令獲得相同的結果,但這種語法使其更具可讀性。sed
也許可以用更簡潔的方式做到這一點。
編輯:我意識到如果您只想更改文件中的 1 個數字,這會起作用。如果我正確理解你的問題,你想重新計算數字每一個行並使用這些新數字創建一個文件。這樣做的最佳方法是包括新行號的計算裡面腳本awk
,這樣您就不必創建 shell 循環,這通常是一個壞主意,因為重複調用諸如awk
, echo
, sed
... 之類的工具最終會變得非常昂貴。你可以這樣做:
if [ -f $PWD/output.txt ]; then
# Remove old output if present in current directory
\rm -f $PWD/output.txt
fi
awk '{ ###calculation here, result store in newNum###; $1=newNum; print}' input.txt > output.txt
例如,如果我想簡單地將每個行號加一:
awk '{$1++; print}' input.txt > output.txt
如果您無法(或不敢)將計算包含在 中awk
,您可以在文件上執行循環,但根據我對bash
腳本的理解,這是相當笨拙的:
if [ -f $PWD/output.txt ]; then
# Remove old output if present in current directory
\rm -f $PWD/output.txt
fi
while read line
do
newNum=###Calculation here for current line###
echo $line | awk -v new=$newNum '$1=new' >> output.txt
done <input.txt
答案2
試試這個..
awk -v num="$variable" '{$1=num}1' input.txt
答案3
這是一個簡短的 python 腳本,可以完成您想要的操作。用法很簡單:給它文件、行開頭的編號以及您希望看到的編號
演示:
bash-4.3$ 貓資料.txt 2 16/10/19 15:30 其他線路 1 2016年10月20日 12:00 在車庫 joe 的車庫取車 3 2016年10月17日 5:30 另一張 bash-4.3$ python renumber.py data.txt 1 15 ['renumber.py', 'data.txt', '1', '15'] bash-4.3$ 貓資料.txt 2 16/10/19 15:30 其他線路 15 2016年10月20日 12:00 在車庫取車 喬的車庫 3 2016年10月17日 5:30 另一張
代碼:
import sys
import os
print(sys.argv)
with open(sys.argv[1]) as inputfile:
with open('/tmp/temp.text','w') as tempfile:
for line in inputfile:
old = line.strip().split()
if old[0] == sys.argv[2]:
old[0] = sys.argv[3]
line = ' '.join(old) + '\n'
tempfile.write(line)
os.rename('/tmp/temp.text',sys.argv[1])