Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed/awk to print lines with matching pattern OR another matching pattern

Tags:

bash

sed

awk

I need to print lines in a file matching a pattern OR a different pattern using awk or sed. I feel like this is an easy task but I can't seem to find an answer. Any ideas?

like image 786
rick Avatar asked Mar 22 '11 00:03

rick


People also ask

How do I print lines between two patterns?

The sed command will, by default, print the pattern space at the end of each cycle. However, in this example, we only want to ask sed to print the lines we need. Therefore, we've used the -n option to prevent the sed command from printing the pattern space. Instead, we'll control the output using the p command.

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

How do I print to the next line in awk?

Original answer: Append printf "\n" at the end of each awk action {} . printf "\n" will print a newline.

What is pattern matching in awk?

Any awk expression is valid as an awk pattern. The pattern matches if the expression's value is nonzero (if a number) or non-null (if a string). The expression is reevaluated each time the rule is tested against a new input record.


2 Answers

The POSIX way

awk '/pattern1/ || /pattern2/{print}' 

Edit

To be fair, I like lhf's way better via /pattern1|pattern2/ since it requires less typing for the same outcome. However, I should point out that this template cannot be used for logical AND operations, for that you need to use my template which is /pattern1/ && /pattern2/

like image 65
SiegeX Avatar answered Nov 10 '22 10:11

SiegeX


Use:

sed -nr '/patt1|patt2/p' 

where patt1 and patt2 are the patterns. If you want them to match the whole line, use:

sed -nr '/^(patt1|patt2)$/p' 

You can drop the -r and add escapes:

sed -n '/^\(patt1\|patt2\)$/p' 

for POSIX compliance.

like image 30
Matthew Flaschen Avatar answered Nov 10 '22 11:11

Matthew Flaschen