2

I have two files:

$ cat File1
A
B
C
$ cat File2
A aaa B
D bbb A
B aaa h

I would like to search patterns from File1 into File2, a sort of what grep -f File1 File2 would do, but searching the patterns reported in File1 only in $1 of File2

Sample output:

$cat File3
A aaa B
B aaa h
1
  • Would it be acceptable to have a modified version of File1: sed 's/^/^/' File1 > File1-anchored? Then use that modified file as pattern file for grep.
    – Philippos
    Aug 17, 2017 at 5:40

3 Answers 3

3

With awk:

awk 'NR==FNR{a[$0]=NR; next} a[$1]' f1.txt f2.txt
  • NR==FNR{a[$0]=NR; next}: for first file (f1.txt) we are putting the record as key to an assiciative array with the corresponding record number as the value

  • a[$1]: for second file (f2.txt), the record is only printed if the first field is a key of array a

Example:

% cat f1.txt                                       
A
B
C

% cat f2.txt                                       
A aaa B
D bbb A
B aaa h

% awk 'NR==FNR{a[$0]=NR; next} a[$1]' f1.txt f2.txt
A aaa B
B aaa h
1

Using join command:

join <(sort file1) <(sort file2)

If the files are sorted.

join file1 file2
0

With bash or any shell that understands process substitution:

$ grep -f <( awk '{ printf("^%s[[:blank:]]\n", $0) }' File1 ) File2
A aaa B
B aaa h

The idea here is to create the correct patterns for grep -f File1 to work directly on File2 by transforming each line in File from something to the regular expression ^something[[:blank:]] (prefix it with a circumflex and suffix it with [[:blank:]]).

The circumflex anchors the pattern to the start of the line and [[:blank:]] forces a match against a space or a tab character.

GNU grep may also read patterns from standard input:

$ awk '{ printf("^%s[[:blank:]]\n", $0) }' File1 | grep -f - File2
A aaa B
B aaa h

The awk command may be replaced by an equivalent sed command (if you prefer sed over awk):

$ sed -e 's/^/^/' -e 's/$/[[:blank:]]/' File1 | grep -f - File2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.