Chr*_*our 123
除非你有GNU awk 4.1.0或更高版本......
你不会有像sed -i
选项这样的选项,所以改为:
$ awk '{print $0}' file > tmp && mv tmp file
Run Code Online (Sandbox Code Playgroud)
注意:这-i
不是魔术,它也是创建一个临时文件,sed
只为你处理它.
截至GNU awk 4.1.0 ...
GNU awk
在4.1.0版(2013年10月10日发布)中添加了此功能.它不像正如-i
发布的注释中所描述的那样提供选项:
新的-i选项(来自xgawk)用于加载awk库文件.这与-f的不同之处在于第一个非选项参数被视为脚本.
您需要使用捆绑的inplace.awk
包含文件来正确调用扩展名,如下所示:
$ cat file
123 abc
456 def
789 hij
$ gawk -i inplace '{print $1}' file
$ cat file
123
456
789
Run Code Online (Sandbox Code Playgroud)
该变量INPLACE_SUFFIX
可用于指定备份文件的扩展名:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{print $1}' file
$ cat file
123
456
789
$ cat file.bak
123 abc
456 def
789 hij
Run Code Online (Sandbox Code Playgroud)
我很高兴这个功能已被添加,但对我来说,实现并不是非常糟糕,因为功能是语言的简洁性和-i inplace
长IMO 8个字符.
这是官方单词手册的链接.
小智 119
在最新的GNU Awk(自4.1.0发布以来)中,它可以选择"inplace"文件编辑:
[...]使用新工具构建的"inplace"扩展可用于模拟GNU"
sed -i
"功能.[...]
用法示例:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 file2 file3
Run Code Online (Sandbox Code Playgroud)
要保留备份:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, "bar") }
> { print }' file1 file2 file3
Run Code Online (Sandbox Code Playgroud)
Yur*_* G. 12
只是一个有效的小黑客
echo "$(awk '{awk code}' file)" > file
Run Code Online (Sandbox Code Playgroud)
Cod*_*ope 11
另一种方法是使用sponge
:
awk '{print $0}' your_file | sponge your_file
Run Code Online (Sandbox Code Playgroud)
您使用'{print $0}'
awk脚本替换的位置以及your_file
要编辑的文件的名称.
sponge
在将输入保存到文件之前完全吸收输入.
小智 5
以下将无法正常工作
echo $(awk '{awk code}' file) > file
Run Code Online (Sandbox Code Playgroud)
这应该工作
echo "$(awk '{awk code}' file)" > file
Run Code Online (Sandbox Code Playgroud)