Search code examples
bashshellunixgrep

grep a pattern and output non-matching part of line


I know it is possible to invert grep output with the -v flag. Is there a way to only output the non-matching part of the matched line? I ask because I would like to use the return code of grep (which sed won't have). Here's sort of what I've got:

tags=$(grep "^$PAT" >/dev/null 2>&1)
[ "$?" -eq 0 ] && echo $tags 

Solution

  • How about using a combination of grep, sed and $PIPESTATUS to get the correct exit-status?

    $ echo Humans are not proud of their ancestors, and rarely invite
      them round to dinner | grep dinner | sed -n "/dinner/s/dinner//p"
    Humans are not proud of their ancestors, and rarely invite them round to 
    
    $ echo $PIPESTATUS[1]
    0[1]
    

    The members of the $PIPESTATUS array hold the exit status of each respective command executed in a pipe. $PIPESTATUS[0] holds the exit status of the first command in the pipe, $PIPESTATUS[1] the exit status of the second command, and so on.