Search code examples
unixgrepcut

finding string in each line using grep


I want to find values from FILE_B to 8th-17th digit only of FILE_A.

FILE_B contains:

 $cat FILE_B
 9237770
 63943100
 6393390990

FILE_A contains

 $cat FILE_A
 50000092280794230000092384245540
 50000092280938880000009237770528
 50000092377704630000009154893441

OUTPUT SHOULD BE

  50000092377704630000009154893441

since 8th-17th (9237770463) digit contains 9237770 (which is in FILE_B)

I have a script but doesn't give me the exact output.

 $cut -c 8-17 FILE_A | grep -f FILE_B

output:

 9237770

Solution

  • Try this command:

    cut -c 8-17 FILE_A |
       grep -nf FILE_B |
         cut -d: -f1 |
           awk 'FNR==NR{a[$1];next};FNR in a' - FILE_A
    
    • add -n option to grep to print line number (suggest fgrep)
    • then cut these numbers
    • use awk to print these lines