3

Let's say I have two files containing attribute names and properties, where different data is stored in two files:

1.txt:

abc12      3@     50
edf13      4@     50
dde8       3@     50

2.txt

abc12      3@     65
edf13      4@     50
dde8       3@     70
dde7       3@     70

I want to grep as follows: first- grep "3@" 1.txt | awk '{print $1}', then grep * 2.txt where star(*) represent output of first grep.

all should be done in a single line from the prompt.

expected output:

abc12      3@     65
dde8       3@     70

Thanks

Cyrus
  • 84,225
  • 14
  • 89
  • 153

3 Answers3

4

With one awk process:

awk 'FNR==NR{if ($2 ~ "3@") a[$1]++; next} a[$1]' 1.txt 2.txt

the first condition{action} means when reading from first file, increase the array element with this first field as hash. The second condition a[$1] is true when this element is one or more, this is checked for the second file and the default action is to print the line.

thanasisp
  • 5,855
  • 3
  • 14
  • 31
1

I think the other answers are better, this is if you insist on grep:

grep "3@" 1.txt| awk '{print $1}' | while read i;do grep $i 2.txt;done
0

Another way with join and grep

join -t $'\t' -o 2.1 2.2 2.3 1.txt 2.txt | grep 3@
ctac_
  • 2,413
  • 2
  • 7
  • 17