使用awk将标头放置在文本文件中 [英] Using awk to put a header in a text file

查看:65
本文介绍了使用awk将标头放置在文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多文本文件,需要根据每个文件上的数据在每个文件上放置一个标题.

I have lots of text files and need to put a header on each one of them depending of the data on each file.

此awk命令完成了任务:

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.

这是我尝试过的:

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

所以我想我不能用cat将它们用作标题,还是我做错了什么?

So I guess I can't use cat to put them as a header, or am I doing something wrong?

预先感谢

推荐答案

我认为您要对循环执行的操作是:

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

,但您实际上并没有真正打算做什么,因为您从不使用 first sum 并在END部分中设置 last 这是一个坏主意,因为它不可能在所有awk中都有效,并且有一个简单的选择.

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.

这篇关于使用awk将标头放置在文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆