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?
            Asked
            
        
        
            Active
            
        
            Viewed 1e+01k times
        
    4 Answers
42
            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
        
- 135,741
 - 24
 - 144
 - 154
 
- 
                    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
        
- 278,309
 - 50
 - 514
 - 539
 
12
            
            
        why dont you want to use grep?
grep -e 'pattern1' -e 'pattern2'
        Vijay
        
- 65,327
 - 90
 - 227
 - 319
 
- 
                    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
 -