2016-12-01 74 views
0

我已經編寫了一個shell腳本,用於替換屬性文件中的某些屬性。但腳本運行後,在替換之前文件末尾沒有空行。使用echo和sed後缺少空行

file=my_file.properties 
file_content=$(cat $file | sed "[email protected]=.*@[email protected]") #making a=b 
file_content=$(echo "${file_content}" | sed "[email protected]=.*@[email protected]") #making x=y 
echo "${file_content}" > $file 

my_file.properties是一樣的東西

1)a=v 
2)b=c 
3)x=b 
4) 

注有空白行中end.These數字只是用於參考顯示空行

+0

在問題中添加文件'my_file.properties'的一些示例內容。 – GurV

回答

1

the Bash manual$(…)Command Substitution(重點煤礦):

Bash執行通過在子環境中執行命令進行擴展,並用命令的標準輸出替換命令替換,刪除任何尾隨的換行符

因此,而不是捕捉命令的輸出到一個變量,你應該捕捉它們到一個臨時文件:

sed "[email protected]=.*@[email protected]" $file | sed "[email protected]=.*@[email protected]" > tmp.tmp 
mv tmp.tmp $file 

或者,如果你使用的是GNU sed的,你可以做到這一點的一條線:

sed -i -e "[email protected]=.*@[email protected]" -e "[email protected]=.*@[email protected]" $file 

-i意味着編輯到位的文件,因此不需要臨時文件。

+0

此外,幾乎沒有理由在腳本中實際使用'cat'。 –

+0

爲什麼,你如何得到文件內容 –

+0

'cat filename | sed ...'涉及兩個進程,'sed ... filename'做同樣的事情,只需要一個。 –