質問

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

役に立ちましたか?

解決 2

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.

他のヒント

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top