Saturday, August 25, 2007

grep multiple strings from a file

Supposed you need to filter different search filter words from a large text file.

Here's a quick entry that covers parsing and filtering multiple strings using grep in a command line.

Grep Multiple Strings From a File

My sample text looks like this

# cat testfile.txt
~~~~~~~~~~~~~~~~~~~~~~~~
apple1
The quick brown fox
apple2
asd
The quick brown fox
apple3
asd
apple4
The quick brown fox
asd
~~~~~~~~~~~~~~~~~~~~~~~~


Here's how to grep multiple search string from a file?

Assuming that we need to filter out the below words from the above file.

apple1
apple2
apple3
apple4


Here's a quick way to filter multiple words from a string or file.

# cat testfile.txt | grep "apple1\|apple2\|apple3"


This gives you all lines with words apple1, apple2 and apple3.

If you wish to grep multiple strings for an exact match from string or file, follow through:

# cat testfile.txt | grep -w "apple1\|apple2\|apple3"


All is done.

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy