Built-in search tool in shell scripts

2019-09-07 03:17发布

问题:

I have an input file "B", containing line numbers referring to specific lines in file "A". I need to search for a text pattern using the line numbers in "B", e.g. first 3 lines of B will be:

385
527
547

So I need to check whether the "pattern" is present between 386 and 526, 528 and 548 in the file "A". I can do this with some complex programming and looping with the help of awk etc., but I want to know the built-in tools and options available in Unix (Solaris) for searching, to make my code simple, e.g., if there is a tool or option to search a pattern between a given line range it will be useful.

回答1:

No looping or complexity needed for awk to match (and print) in a range:

awk 'NR>start && NR<end && /pattern/'

A bit trickier to convert file B content to the right awk condition, but this does it:

echo "($(awk 'NR==1{r1=$1;next}
              NR>2{printf"||"}
              {printf"(NR>%d&&NR<%d)",r1,$1;r1=$1}
              END{if(NR<2)printf"0"}' B))&&/yourpattern/"|
  awk -f- A

Perhaps slightly simpler would be to pre-filter the ranges using sed, and then grep for the pattern:

awk 'NR==1{r1=$1;next}
     $1>r1+1{printf"%d,%dp\n",r1+1,$1-1;r1=$1}' B|
  sed -nf- A|
  grep 'yourpattern'


标签: shell unix awk