Using awk to put a header in a text file

青春壹個敷衍的年華 提交于 2021-02-19 08:48:05

问题


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 'NR==1{first=$1}{sum+=$1;}END{last=$1;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=$1}{sum+=$1;}END{last=$1;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?

Thanks in advance


回答1:


I THINK what you're trying to do with your loop is:

for i in *.txt
do
    echo "Processing $i"
    awk 'NR==1{first=$1}{sum+=$1}END{last=$1;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.

If you update your question with some sample input and expected output we can help you.




回答2:


UPDATE:

with awk:

awk 'BEGIN{print "header"}1' test.txt

without awk:

with cat & echo:

cat <(echo "header") test.txt

(OR)

using tac:

tac test.txt | echo "header" >> test.txt | tac test.txt


来源:https://stackoverflow.com/questions/21852630/using-awk-to-put-a-header-in-a-text-file

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