Does sed have an option similar to grep -q
, where it returns a 1 or 0 depending on if it actually finds a string match or not?
The reason I ask is in some cases I use sed
in particular ways, like finding the first match after a given line number, or setting a capture group and acquiring a string that way, so I wanted to see if sed
had anything built in that would check if anything is returned because I want to throw an error back to the user and exit my bash script if a match isn't found
You are much better off using grep -q
for this, but if you ABSOLUTELY want to use sed
then here is how you could replicate the functionality...
cat myFile | sed -n "/myString/p" | wc -l
This will pipe out the number of occurences of "myString" in a file. From here you could do a simple test to see if the number is greater then 0, if so return 1, if not return 0. Here is a script demoing how to accomplish this...
#!/bin/bash
count=$(cat myFile | sed -n "/\myString/p" | wc -l)
final=0
if [ count -gt 0 ]; then
final=1
else
final=count
fi
echo final
The script above will print out 1 or 0, 1 if the string was found and 0 if it wasn't (note: I haven't checked this, but there's no reason why it wouldn't work).
Again, grep -q
is the tool for the job and I would recommend using it if at all possible.
You can set the exit code using the q
command in sed
.
q [exit-code]
Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension.
See also this answer for a clue.
EDIT:
As @cbuckley kindly linked to, you can find directions here.
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