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
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.
-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.
You can use option -A (after) and -B (before) in your grep command. Try grep -nri -A 5 -B 5 .
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.
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.
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
:
/$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./s/
: This says you will be doing a substitution/$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.//
: This is what you're substituting for $PAT
. It is null. Therefore, you're deleting $PAT
from the line./p
: This final p
says to print out the line.Thus:
sed
not to print out the lines of the file as it processes them.$PAT
.s
command (substitution) to remove the pattern.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With