Search code examples
sedbsd

How to delete line that doesn't contain pattern 1 or pattern 2


Using sed I can do this

sed -i '' '/myPattern/!d' file

But how can I make it compare against 2 patterns? So it only deletes lines that do not have at least 1 of the 2 patters?


Solution

  • You may use multiple commands with -e and use -n and p instead of !d:

    sed -n -i '' -e '/myPattern/p' -e '/myPattern2/p' file
    

    Usually I prefer awk for that task since you can use boolean logic, like:

    awk '/pattern1/ || /pattern2/' file
    

    or

    awk '/pattern1/ && /pattern2/' file
    

    and so on.


    Btw, having GNU awk you can also edit files in place:

    gawk -i inplace '/pattern1/||/pattern2/' file