JFS31 JFS31 - 1 year ago 68
Linux Question

Use regex in grep while while using two files

I know that you can use regex in grep and use patterns from a file to search another file but can you combine these two.

For example from the file where the patterns come from (with the -f option for use patterns from a file) I only want to use the first column to search the second file.

I tried this:

grep -E '^(*)\b' -f file_1 file_2 > file_3

To grep the first column from file_1 with the * wildcard and but it is not working. Any ideas?

Answer Source

Grep doesn't use wildcards for patterns, it uses regular expressions, so (*) makes little sense.

If you want to extract the first column from a file, use cut -f1 or awk '{print $1}' (or sed or perl or whatever to extract it), the redirect to grep using the special - (i.e. standard input) as the source file:

cut -f1 file1 | grep -f- file_2 > file_3
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download