问题
I have a question. This is my input file.
#!/bin/bash
name="eq6"
tmp=$(mktemp) || exit 1
for index in {1..2}
do
awk 'f;/hbonds_Other-SOL/{f=1}' "${name}_$index.ndx" > "$tmp" && mv "$tmp" "${name}_$index.ndx"
done
Is it possible do this only in awk? I don't want to call awk in every for loop.
This is my input eq6_1.ndx
98536 98539 98542 98545 98548
[ hbonds_Other-SOL ]
8 9 76759
eq6_2.ndx
98542 98545 98548
[ hbonds_Other-SOL ]
8 9 65281
Expected output - print all lines from all files which are after "hbonds_Other-SOL"
eq6_1.ndx
8 9 76759
eq6_2.ndx
8 9 65281
回答1:
With GNU awk for "inplace" editing:
$ head *.ndx
==> eq6_1.ndx <==
98536 98539 98542 98545 98548
[ hbonds_Other-SOL ]
8 9 76759
==> eq6_2.ndx <==
98542 98545 98548
[ hbonds_Other-SOL ]
8 9 65281
$ awk -i inplace 'FNR==1{f=0} f; /hbonds_Other-SOL/{f=1}' eq6_{1..2}.ndx
$ head *.ndx
==> eq6_1.ndx <==
8 9 76759
==> eq6_2.ndx <==
8 9 65281
There are various options with other awk versions but the simplest is probably:
dir=$(mktemp -d) &&
awk -v dir="$dir" 'FNR==1{close(out); out=dir"/"FILENAME; f=0} f{print > out} /hbonds_Other-SOL/{f=1}' eq6_{1..2}.ndx &&
mv "$dir"/* . &&
rmdir "$dir"
来源:https://stackoverflow.com/questions/65980443/instead-using-awk-in-for-loop-in-bash-through-all-files-do-something-only-in-a