while read vl ; do grep "^$vl " file2 ; done < file1
read
looks for input terminated by a newline and places in the variable vl
. By wrapping this in a while
loop this is repeated for all contents of STDIN
. By using < file1
we redirect the contents of file1
into STDIN, so the loop repeats for all contents of file1
. For each line of file1
(stored in vl
) we grep in file2
with the search term prefixed by ^
. This ties the search term to be at the beginning of the line in file2
. I've also added a space at the end of the grep search string (I'm assuming file2's column separator is a space), so that it will only match exactly and not sub matches (if the search term is foo and file2
has a row with foobar as column one it will not get matched). Replace that space with whatever your field separator of file2
is if it is not space.
If you can change file1 at will then:
sed -i 's/^\(.*\)$/^\1 /' file1
and then your original grep -f
will work (note again I've used space as a separator - after the \1
).