2012-02-29 58 views
6

林試圖在使用awk文件一行的替代,例如改變使用awk

行改變這樣的:

e1 is (on) 

e2 is (off) 

到:

e1 is (on) 

e2 is (on) 

使用命令:

awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba > ~/Documents/Prueba 

this使替代,但文件結束空白!

回答

18

另一個答案,使用不同的工具(SED,和-i(到位)標誌)

sed -i '/e2/ s/off/on/' ~/Documents/Prueba 
17

您的awk是正確的,但是您將重定向到與原始文件相同的文件。這會導致原始文件在被讀取之前被覆蓋。您需要將輸出重定向到其他文件。

awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba > ~/Documents/Prueba.new 

如果需要,可以重新命名爲Prueba.new。

+2

+1。強調「原始文件在被讀取之前被覆蓋* – 2012-02-29 17:07:46

0

您不能重定向到與輸入文件相同的文件。選擇另一個文件名。

>將首先清空您的文件。

2

正如其他的答案,並在問題「Why reading and writing the same file through I/O redirection results in an empty file in Unix?」解釋說,讀前殼重定向摧毀你的輸入文件。

要解決該問題而不明確訴諸臨時文件,請查看moreutils集合中的sponge命令。

awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba | sponge ~/Documents/Prueba 

或者,如果GNU awk安裝在您的系統上,則可以使用in place extension

gawk -i inplace '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba