如何使用 awk 命令将查找输出写入同一文件
awk '/^nameserver/ && !modif { printf("nameserver 127.0.0.1\n"); modif=1 } {print}' testfile.txt
它正在显示输出,但我想将输出写入同一个文件。在我的示例中 testfile.txt
。
awk '/^nameserver/ && !modif { printf("nameserver 127.0.0.1\n"); modif=1 } {print}' testfile.txt
It is displaying output but I want to write the output to same file. In my example testfile.txt
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
本身不可能。您需要第二个临时文件,因为您无法读取和覆盖同一文件。类似于:
mktemp
程序对于生成唯一的临时文件名非常有用。有一些避免临时文件的技巧,但它们主要依赖于缓存和读取缓冲区,并且对于较大的文件很快就会变得不稳定。
Not possible per se. You need a second temporary file because you can't read and overwrite the same file. Something like:
The
mktemp
program is useful for generating unique temporary file names.There are some hacks for avoiding a temporary file, but they rely mostly on caching and read buffers and quickly get unstable for larger files.
从 GNU Awk 4.1.0 开始,就有了“inplace”扩展,所以你可以这样做:
要保留原始文件的备份副本,请尝试以下操作:
这可以用来模拟 GNU
sed -i
特征。请参阅:启用就地文件编辑
Since GNU Awk 4.1.0, there is the "inplace" extension, so you can do:
To keep a backup copy of original files, try this:
This can be used to simulate the GNU
sed -i
feature.See: Enabling In-Place File Editing
尽管使用临时文件是正确的,但我不喜欢它,因为:
你必须确保不要删除另一个临时文件(是的,你可以使用 mktemp - 这是一个非常有用的工具)
你必须小心删除它(或像 thiton 所说的那样移动它),包括当你的脚本崩溃或停止时在结束之前(因此在脚本末尾删除临时文件并不明智)
它在磁盘上生成 IO(好吧,不是那么多,但我们可以让它更轻)
所以我避免临时文件的方法很简单:
请注意在获取 awk 命令的输出时和使用 echo 时使用双引号(如果不这样做,则不会有换行符)。
Despite the fact that using a temp file is correct, I don't like it because :
you have to be sure not to erase another temp file (yes you can use mktemp - it's a pretty usefull tool)
you have to take care of deleting it (or moving it like thiton said) INCLUDING when your script crash or stop before the end (so deleting temp files at the end of the script is not that wise)
it generate IO on disk (ok not that much but we can make it lighter)
So my method to avoid temp file is simple:
Note the use of double quotes either when grabbing the output from the awk command AND when using echo (if you don't, you won't have newlines).
当在一句话中看到“awk”和“不可能”时,必须记下一笔。这是一个仅使用 awk 的解决方案,无需创建临时文件:
Had to make an account when seeing 'awk' and 'not possible' in one sentence. Here is an awk-only solution without creating a temporary file:
您还可以使用 moreutils 中的
sponge
。例如,
删除重复行并将
第二列乘以 10。
You can also use
sponge
from moreutils.For example
removes duplicate lines and
multiplies the second column by 10.
尝试在 awk 文件中包含语句,以便可以在新文件中找到输出。这里的total是一个计算值。
Try to include statement in your awk file so that you can find the output in a new file. Here total is a calculated value.
这种内联写作对我有用。将打印的输出重定向回原始文件。
This inline writing worked for me. Redirect the output from print back to the original file.