bash 使用 awk 将标题放入文本文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21852630/
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
Using awk to put a header in a text file
提问by JM88
I have lots of text files and need to put a header on each one of them depending of the data on each file.
我有很多文本文件,需要根据每个文件上的数据在每个文件上放置一个标题。
This awk command accomplishes the task:
这个 awk 命令完成了任务:
awk 'NR==1{first=}{sum+=;}END{last=;print NR,last,"L";}' my_text.file
But this prints it on the screen and I want to put this output in the header of each of my file, and saving the modifications with the same file name.
但这会将它打印在屏幕上,我想将此输出放在每个文件的标题中,并使用相同的文件名保存修改。
Here is what I've tried:
这是我尝试过的:
for i in *.txt
do
echo Processing ${i}
cat awk 'NR==1{first=}{sum+=;}END{last=;print NR,last,"L";}' "${i}" ${i} > $$.tmp && mv $$.tmp "${i}"
done
So I guess I can't use cat to put them as a header, or am I doing something wrong?
所以我想我不能用 cat 把它们作为标题,还是我做错了什么?
Thanks in advance
提前致谢
回答by MLSC
UPDATE:
更新:
with awk
:
与awk
:
awk 'BEGIN{print "header"}1' test.txt
without awk
:
没有awk
:
with cat
& echo
:
与cat
& echo
:
cat <(echo "header") test.txt
(OR)
(或者)
using tac
:
使用tac
:
tac test.txt | echo "header" >> test.txt | tac test.txt
回答by Ed Morton
I THINK what you're trying to do with your loop is:
我认为你试图用你的循环做的是:
for i in *.txt
do
echo "Processing $i"
awk 'NR==1{first=}{sum+=}END{last=;print NR,last,"L"}' "$i" > $$.tmp &&
cat "$i" >> $$.tmp &&
mv $$.tmp "$i"
done
but it's not clear what you're really trying to do since you never use first
or sum
and setting last
in the END section is a bad idea as it will not work across all awks and there's a simple alternative.
但不清楚你真正想要做什么,因为你从不使用first
orsum
并且last
在 END 部分设置是一个坏主意,因为它不适用于所有 awk 并且有一个简单的替代方案。
If you update your question with some sample input and expected output we can help you.
如果您使用一些示例输入和预期输出更新您的问题,我们可以为您提供帮助。