change a line with awk

冷暖自知 提交于 2020-01-22 13:59:45

问题


Im trying to make a substitution of a single line in a file with awk, for example

changing this:

e1 is (on)

e2 is (off)

to:

e1 is (on)

e2 is (on)

use command:

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

this makes the substitution but the file ends blank!


回答1:


Another answer, using a different tool (sed, and the -i (in place) flag)

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



回答2:


Your awk is correct, however you are redirecting to the same file as your original. This is causing the original file to be overwritten before it has been read. You'll need to redirect the output to a different file.

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

Rename Prueba.new afterwards if necessary.




回答3:


You can also use cat to read the file first, then use pipe to redirect to stdout, then read with awk from stdin:

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

I believe the dash - is optional, since you're only reading stdin.

Some interesting documentation: https://www.gnu.org/software/gawk/manual/html_node/Naming-Standard-Input.html




回答4:


As explained by the other answers and in the question "Why reading and writing the same file through I/O redirection results in an empty file in Unix?", the shell redirections destroy your input file before it is read.

To solve that problem without explicitly resorting to temporary files, have a look at the sponge command from the moreutils collection.

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

Alternatively, if GNU awk is installed on your system, you can use the in place extension.

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



回答5:


You cannot redirect to the same file as input file. Chose another file name.

The > will empty you file at the first place.



来源:https://stackoverflow.com/questions/9503159/change-a-line-with-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!