grep a string to another file

60 views Asked by At

I have two files wherein:

cat A.txt

 5000000000000022805787
 5000000000009228662688
 5000000000009253546657

cat B.txt

 22805177, 22805179
 9228662680, 9228662689
 22805787, 22805789

output:

 9228662680, 9228662689
 22805787, 22805787

I want to grep numbers in A.txt (after zeroes) from B.txt. I have a code below but doesn't display an output.

 awk '{anum=substr($1,3,19); sub(/^0+/, "", anum); print anum}' A.txt | grep -nf B.txt

PS

 anum:
 2280578
 922866268
 925354665
2

There are 2 answers

0
nu11p01n73R On BEST ANSWER

You should be doing it in the other way round.

You need to search using the patterns produced by awk. So you can write something like

$ grep "$(awk '{anum=substr($1,3,19); sub(/^0+/, "", anum); print anum}' a)" b
9228662680, 9228662689
22805787, 22805789

PS You can do this thing entirely using awk.

0
bkmoney On

You are missing a dash to specify that the file is coming from the pipe

awk '{anum=substr($1,3,19); sub(/^0+/, "", anum); print anum}' A.txt | grep -f - B.txt

This outputs

9228662680, 9228662689
22805787, 22805789