Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I want to use unix's grep function to pull out multiple lines (with different key words) from a file in one command line.

e.g. i have something like

doc-A1-151
file-A2-15646
table-A3-1654
file-B1-15654
doc-B2-15654
table-B3-13546
file-C1-164654
doc-C2-16354
table-C3-13565

and i want a sub-version of the file with just the A1, B3, and C2 lines.

how do i do that?

share|improve this question
    
Take a look at this post:theunixshell.blogspot.com/2014/03/… –  Vijay Apr 18 at 19:17

2 Answers 2

up vote 3 down vote accepted

Grep allows you to use regular expressions to match patterns within the file using the -E flag, or you can use the egrep command which is equivalent to grep -E:

grep -E 'A1|B3|C2' filename

or

egrep 'A1|B3|C2' filename

The vertical bar, |, is the OR operator meaning match string A1 or B3 or C2.

Regular expression syntax varies from tool to tool, but generally the syntax is the same. Here is a regex test harness for Ruby that I use frequently to test and build regular expressions: http://rubular.com/r/mJyIMO5hJN

However, any introduction to regular expressions should be prefaced with a warning that they are limited in their capabilities, and the adage is:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

share|improve this answer
    
thanks i might use that one next time –  Kirstin Oct 6 '12 at 7:11

Found it. Put the terms in a text file separated by new lines, then enter that as the pattern to match with the -f flag.

pattern_file.txt:

A1
B3
C2

Command:

grep -f pattern_file.txt input_file.txt
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.