I’m looking for a shell command (a one-liner) that eats all of its standard input if that input matches a string. Otherwise, it just outputs its input.
Likewise, how about a command that eats all of its input if it doesn’t match the string.
Presumably sed or awk can do it, but it’s beyond my fu. I can easily do it with a shell script but I’d prefer a single command.
This is useful in crontab so that you only receive an email if the output of a command fails (i.e. matches a string).
So, below, what are “eatIfMatch” and “eatIfNoMatch”?
Thanks for any ideas.
$ cat matchFile
This file
will match the
pattern
$ cat noMatchFile
This file
doesn’t quite
Match
though
$ eatIfMatch match < matchFile
$ eatIfMatch match < noMatchFile
This file
doesn’t quite
Match
though
$ eatIfNoMatch match < matchFile
This file
will match the
pattern
$ eatIfNoMatch match < noMatchFile
$
CodePudding user response:
This might work for you (GNU sed and Bash):
eatIfMatch(){ sed -zn '/'"$1"'/!p' "$2"; }
eatIfMatch match fileMatch
eatIfMatch match fileNoMatch
This file
doesn’t quite
Match
though
eatIfNoMatch(){ sed -zn '/'"$1"'/p' "$2"; }
eatIfNoMatch match fileMatch
This file
will match the
pattern
eatIfNoMatch match fileNoMatch
Function eatIfMatch
accepts regexp to match and if it does eats the file.
Function eatIfNoMatch
accepts regexp to mat and if it does not eats file.
CodePudding user response:
Assign the input to a variable. Check if the variable contains the string. If not, it prints the string.
eatIfMatch() {
local var=$(cat)
if [[ $var != *"$1"* ]]
then printf "%s\n" "$var"
fi
}
If you want awk
, it's essentially the same logic
awk '/match/ {found=1} {all = all "\n" $0} END {if(found) print substr(all, 1)}'