bash 用 awk 换一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9503159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:43:20  来源:igfitidea点击:

change a line with awk

bashawk

提问by Josepas

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

例如,我试图用 awk 替换文件中的一行

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!

这进行了替换,但文件以空白结尾!

回答by David Souther

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

另一个答案,使用不同的工具(sed 和 -i(就地)标志)

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

回答by qbert220

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 是正确的,但是您重定向到与原始文件相同的文件。这导致原始文件在读取之前被覆盖。您需要将输出重定向到不同的文件。

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

Rename Prueba.new afterwards if necessary.

如有必要,请稍后重命名 Prueba.new。

回答by GabrielF

You can also use catto read the file first, then use pipeto redirect to stdout, then read with awkfrom stdin:

您也可以使用cat先读取文件,然后使用pipe重定向到标准输出,然后使用awk标准输入读取:

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

一些有趣的文档:https: //www.gnu.org/software/gawk/manual/html_node/Naming-Standard-Input.html

回答by Charles Plessy

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.

正如其他答案和问题“为什么通过 I/O 重定向读取和写入同一个文件会导致 Unix 中的文件为空?”所解释的那样,shell 重定向会在输入文件被读取之前将其销毁。

To solve that problem without explicitly resorting to temporary files, have a look at the spongecommand from the moreutilscollection.

要在不明确诉诸临时文件的情况下解决该问题,请查看moreutils集合中的海绵命令。

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.

或者,如果您的系统上安装了 GNU awk,您可以使用就地扩展

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

回答by kev

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

您不能重定向到与输入文件相同的文件。选择另一个文件名。

The >will empty you file at the first place.

>将清空你的文件摆在首位。