Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 757
Dennis Avatar asked Jun 20 '11 22:06

Dennis


People also ask

How do you grep for lines that don't match?

To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters). By default, grep is case-sensitive.

Which of the grep command option will select non matching lines from given file?

-v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words.

How do you grep with surrounding lines?

You can use option -A (after) and -B (before) in your grep command. Try grep -nri -A 5 -B 5 .

Does grep return the whole line?

The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.


1 Answers

You could use sed:

$ sed -n "/$PAT/s/$PAT//p" $file

The only problem is that it'll return an exit code of 0 as long as the pattern is good, even if the pattern can't be found.


Explanation

The -n parameter tells sed not to print out any lines. Sed's default is to print out all lines of the file. Let's look at each part of the sed program in between the slashes. Assume the program is /1/2/3/4/5:

  1. /$PAT/: This says to look for all lines that matches pattern $PAT to run your substitution command. Otherwise, sed would operate on all lines, even if there is no substitution.
  2. /s/: This says you will be doing a substitution
  3. /$PAT/: This is the pattern you will be substituting. It's $PAT. So, you're searching for lines that contain $PAT and then you're going to substitute the pattern for something.
  4. //: This is what you're substituting for $PAT. It is null. Therefore, you're deleting $PAT from the line.
  5. /p: This final p says to print out the line.

Thus:

  • You tell sed not to print out the lines of the file as it processes them.
  • You're searching for all lines that contain $PAT.
  • On these lines, you're using the s command (substitution) to remove the pattern.
  • You're printing out the line once the pattern is removed from the line.
like image 187
David W. Avatar answered Nov 01 '22 14:11

David W.