The simplest solution is to just use the file as a pattern list:
Code:
grep -f file2.txt file1.txt
The only problem with this is that it will match numbers found anywhere in the line, not just at the front. But you can use
bash's
process substitution to pre-filter the list and turn the entries into regex patterns.
Code:
grep -f <( sed -n '/^$/! s/^/^/p' file2.txt ) file1.txt
The
sed command adds a "
^" to the start of each non-empty line, so that grep will treat is as "<start of line><number>".
Another option would be to loop through the file:
Code:
while read -r num; do
if [[ $num ]]; then
grep "^$num" file1.txt
fi
done <file2.txt
But this does require a separate instance of
grep for each line, and so is less efficient.