Does sed have an option just for checking existence of string in file?
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.
Related videos on Youtube
user2150250
Updated on September 18, 2022Comments
-
user2150250 over 1 year
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 ifsed
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-
metalhead about 11 yearswhy not just use grep?
-
Chris Seymour about 11 years@user2150250 not with
sed
I don't believe, you can withawk
however. -
user2150250 about 11 years@sudo_O Thank you for your helpful answer. That's all I was asking. I don't see why my inquiry deserved two votes down, but it's been said before, the sed community is picky (no pun intended).
-
eldris about 11 yearsCould you chain it like this grep -q 'pattern' file && sed 's/pattern/' file || echo "cannot make requested change" (example found at unix.com/shell-programming-scripting/…) or can you 100% not use grep?
-
Chris Seymour about 11 years@user2150250 I believe if you would have asked the question in the manner of your first comment which gives sane reason for why you would do this i.e. you want to do more than a simple match, then you wouldn't have got such a negative response, people can be quick to vote, something to bare in mind
-
user2150250 about 11 years@eldris yeah I suppose I could use something like that in most of my cases but in my more complicated sed's like using capture groups or finding first match after line #, I'm not sure grep could utilize the syntax in the same way and I'm not too familiar with porting "sed fucntionality" over to grep unfortunately. Thank you for the helpful link and comment though.
-