Instead using awk in for loop in bash through all files - do something only in awk

大城市里の小女人 提交于 2021-02-15 07:37:18

问题


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

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