KianStar
KianStar

Reputation: 177

How to redirect output of awk to a file?

I have this awk command to replace the occurrance of "proto" in file.txt by strings found in replacement.txt,

awk 'FNR==NR{a[++i]=$0; next} /proto/{sub(/proto/, a[++j])} 1' replacement.txt file.txt

It works perfectly, but the original file is not edited. I used >> to redirect it to file, but the output is not redirected

awk 'FNR==NR{a[++i]=$0; next} /proto/{sub(/proto/, a[++j])} 1' replacement.txt file.txt >> "file.txt"

Could anybody give me a hint?

Upvotes: 0

Views: 627

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185189

With gawk > 4.1:

gawk -i inplace 'FNR==NR{a[++i]=$0; next} /proto/{sub(/proto/, a[++j])} 1' replacement.txt file.txt

If you don't have this feature, use a temporary filename, then mv temp file.txt

Upvotes: 1

Jotne
Jotne

Reputation: 41456

Her is how you do it with awk

awk 'some program' file > tmp && mv tmp file

For your data:

awk 'FNR==NR{a[++i]=$0; next} /proto/{sub(/proto/, a[++j])} 1' replacement.txt file.txt > tmp && mv tmp file.txt

Upvotes: 2

Related Questions