The grep
command gives out an exit status:
$echo "foo.bar" | grep -o foo
foo
$echo $?
0
$echo "foo.bar" | grep -o pop
$echo $?
1
But I need to use sed
and I realized that it has no exit status:
$echo "foo.bar" | sed 's/bar.*$//'
foo.
$echo $?
0
$echo "foo.bar" | sed 's/pop.*$//'
foo.bar
$echo $?
0
I know that I should play around with the -q
option, but I have not succeeded.
You can use qn to quit with exit status n - but to make that useful, you will also need to use some Branching and Flow Control:
It is probably best to choose a value for n that is distinct from one of the standard exit status values:
So for example
whereas
If you want to omit the default printing of the pattern space, then replace
q
byQ
(note thatQ
is a GNU extension).Here's how to search regex with sed, and highlight matches, or return exit code (5) if no match found:
This is input.txt:
Here's my function to Print all + Highlight matches + Return exit code:
When there's no match, it will return exit code (5). You can use it with cat and pipe | as well:
* No match found *
Thanks to https://unix.stackexchange.com/a/405725/43233 - I'm using it + sed quit option.
duplicate of answer https://stackoverflow.com/a/61808364/10440128
output:
so, to check if sed did replace something:
output:
limitation: can handle only one substitution. so this does not work:
error:
(sed treats everything after
w
as a file path)workaround: use multiple sed calls