I am searching for the string ::=BEGIN
and I want to apply a condition to check if the word has been found.
So, what I mean is something along these lines:
if (sed command does find a match for "::=BEGIN")
then i=1
else i=0
Also, I want the 1 (for yes found) and 0 (not found) to be put into the variable "i".
Please help me out. Also provide a explanation to the solution! Thanks!
Best Answer
grep
does that job well enough.What the code does is simply running a quiet search within subshell.
&&
, or logical AND operand, checks if the first command succeeded, and if it did, then it runsecho "FOUND"
.||
checks if that echo has been run, i.e., if we found anything. Second echo runs only if the first command failed.Here's an
awk
version:Basic idea here is to set
i
toNOTFOUND
, and if we find the string - change it toFOUNDIT
. At the end after the first set of has finished processing file, we will printi
, and it will tell us if we found something or not.Edit: In the comment you mentioned that you want to place the result into a variable. Shell already provides a variable that reports exit status of the previous command,
$0
. Exit status 0 means success, everything else - fail. For instance,If you want to use exit status in a variable, you can do it like so :
MYVAR=$(echo $?)
. Remember , $? report exit status of previous command. So you must use this right after the grep command.If you want to still use my earlier awk and grep one-liners, you can use same trick
MYVAR=$()
and place whatever command you want between the braces. The output will get assigned to variableMYVAR
.