29

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

Yang
  • 7,312
  • 7
  • 45
  • 64
rick
  • 1,025
  • 4
  • 20
  • 29

4 Answers4

39

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/

SiegeX
  • 128,491
  • 23
  • 138
  • 153
  • thanks, this worked great. i can never figure out whether sed or awk is appropriate for a given task. is there any big difference i am missing? or different ways to do the same thing? – rick Mar 22 '11 at 01:45
  • @rick, yes there is. awk is a programming language. sed is not really so practically. (although its turing complete). – kurumi Mar 22 '11 at 01:53
  • 1
    @rick I generally only use `sed` for simple text replacement as in `s/foo/bar/g` or what have you. For cases where you want to print out only a portion of a given line, I generally look to `awk` for most applications although `sed` can be coerced to do it with some regex magic. If you ever have a problem that deals with any sense of 'fields' whatever the delimiter may be, you pretty much always want to go with `awk` in that case. Also, it is never correct to pipe the output of `awk` to `grep` or vice versa. You can always combine those two inside of `awk`. – SiegeX Mar 22 '11 at 21:01
28

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.

Matthew Flaschen
  • 268,153
  • 48
  • 509
  • 534
12

why dont you want to use grep?

grep -e 'pattern1' -e 'pattern2'
Vijay
  • 62,703
  • 87
  • 215
  • 314
  • One possible reason is "the -P option only supports a single pattern", hence with multiple `-e`s, you won't be able to use Perl RegExp such as \d with GNU's Grep. – xuchunyang Jun 01 '20 at 05:34
  • How about something like `egrep 'pattern1|pattern2'`? – jena Mar 23 '21 at 12:40
8

awk '/PATT1|PATT2/ { print }'

lhf
  • 67,570
  • 9
  • 102
  • 136