9

I am using the grep -f function to extract lines from a file which match a particular pattern. Let's say my pattern file is pattern.txt, as follows.

1 2 3 4 5 

And the file against which I am matching this pattern is file.txt,

1::anv 2::tyr 3::yui 4::fng 5::gdg 6::ere 7::rer 8::3rr 9::gty 

Now when I do a grep -f pattern.txt file.txt, I am getting this ->

1::anv 2::tyr 3::yui 4::fng 5::gdg 8::3rr 

The last line in the output above, is causing my problem. How do I modify this grep command so as to get the output (showing correct correspondences) as follows?

1::anv 2::tyr 3::yui 4::fng 5::gdg 
1
  • I tried grep "more patt.txt" file.txt | awk -F '::' '{ print $1 " "$2}' But this also gives me the same problem. Commented May 31, 2012 at 11:59

2 Answers 2

12

Add ^ before your patterns so that grep will match a line start with your pattern. If your pattern is actually set of numbers, You don't need a list of patterns. Just use ^[1-5]:.

Sign up to request clarification or add additional context in comments.

1 Comment

just be aware that ^1 will match 10:, etc. if the numbers ever get that big.
7

Well, there are lots of possible solutions. You are telling grep to find all lines containing a 3, and the line '8::3rr' does in fact contain a 3. so you need to be more specific in what you're looking for.

For example, you can change the patterns to '1:', '2:', etc. to match only numbers followed by a colon. Or you could change them to '^1', '^2', etc. to match only numbers at the beginning of the line. It depends on your data, but probably you want both, so that your search for '1:' doesn't match '21:' and your search for '^5' doesn't match '53:'. In which case your patterns file would like like this:

^1: ^2: ^3: ^4: ^5: 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.