onlyf onlyf - 4 months ago 16x
Perl Question

Sed - Print Lines that match two patterns

i have the following problem. My file looks like this :


and i m trying to print only lines that match both patterns, anywhere on the line. I want to print only lines that match two patterns, the first pattern being on columbs 2:1 (08) and the second pattern being the word (RAD). I ve tried to do this with grep :

grep -o '.[0-1][1-8]*RAD' FILEIN

and the only response i get is that FILEIN is a binary file. I ve also tried with sed this :

sed -n '/[0-1][1-8]*RAD/p' FILEIN

but i have a feelign the * is not expanded. I ve managed to make it work by looking for two patterns in succession, like :

sed -n '/RAD/p' FILEIN | sed '/^108/p'

and this works, but the file i ll be using as input is potentially huge, and i m not sure that piping a stream into another is time efficient. Could someone help me? Awk or Perl are welcome too. Thank you


You can add an -a option to grep to force it to read a file as text.

sed is a scripting language; you can combine multiple conditions and actions easily.

sed -n '/regex1/!d;/regex2/p' files...

(If no match on the first regex, delete this line and take the next one. Otherwise, if it matches the second regex, print.)

The same is also easy -- perhaps even easier -- in Awk.

awk '/regex1/ && /regex2/' files...