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
sed 's/^/^/' File1 > File1-anchored
? Then use that modified file as pattern file forgrep
.