Check string after cat command in bash - string

How do I check if a string is contained in the text produced by a cat command in bash? I want to execute a certain action if the string is found in the text.

Like this, using the pipe :
cat my_file | grep my_string
if [ ! $(cat my_file.txt | grep my_text) == "" ]
then echo "exists"
else
echo "not exists"
fi;

Piping to grep is fine if it's a one-time match. Otherwise in bash you can match strings using patterns (==) or regexes (=~) like this:
# date looks like "Mon, Jun 22, 2020 11:04:54 AM"
today=$(date)
[[ $today == Mon* ]] && echo "It's the start of the week"
[[ $today =~ ^(Tue|Wed|Thu) ]] && echo "It's the middle of the week"
[[ $today == Fri* ]] && echo "Thank God It's Friday!"
This is really a comment on the other answer - you can just directly test the exit status of a command
# grep succeeds (exit status 0) if there's a match
# grep -q is to suppress the output of the matched line
# we just care whether there is a match or not
if grep -q my_text my_file.txt; then
echo "exists"
else
echo "not exists"
fi

Simply:
if grep -q my_text file; then
echo "exists"
else
echo "not exists"
fi

Related

LINUX script bash [duplicate]

I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
What's wrong in my code?
if grep -q SomeString "$File"; then
Some Actions # SomeString was found
fi
You don't need [[ ]] here. Just run the command directly. Add -q option when you don't need the string displayed when it was found.
The grep command returns 0 or 1 in the exit code depending on
the result of search. 0 if something was found; 1 otherwise.
$ echo hello | grep hi ; echo $?
1
$ echo hello | grep he ; echo $?
hello
0
$ echo hello | grep -q he ; echo $?
0
You can specify commands as an condition of if. If the command returns 0 in its exitcode that means that the condition is true; otherwise false.
$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$
As you can see you run here the programs directly. No additional [] or [[]].
In case if you want to check whether file does not contain a specific string, you can do it as follows.
if ! grep -q SomeString "$File"; then
Some Actions # SomeString was not found
fi
In addition to other answers, which told you how to do what you wanted, I try to explain what was wrong (which is what you wanted.
In Bash, if is to be followed with a command. If the exit code of this command is equal to 0, then the then part is executed, else the else part if any is executed.
You can do that with any command as explained in other answers: if /bin/true; then ...; fi
[[ is an internal bash command dedicated to some tests, like file existence, variable comparisons. Similarly [ is an external command (it is located typically in /usr/bin/[) that performs roughly the same tests but needs ] as a final argument, which is why ] must be padded with a space on the left, which is not the case with ]].
Here you needn't [[ nor [.
Another thing is the way you quote things. In bash, there is only one case where pairs of quotes do nest, it is "$(command "argument")". But in 'grep 'SomeString' $File' you have only one word, because 'grep ' is a quoted unit, which is concatenated with SomeString and then again concatenated with ' $File'. The variable $File is not even replaced with its value because of the use of single quotes. The proper way to do that is grep 'SomeString' "$File".
Shortest (correct) version:
grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"
can be also written as
grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"
but you dont need to explicitly test it in this case, so the same with:
grep -q "something" file && echo "yes" || echo "no"
##To check for a particular string in a file
cd PATH_TO_YOUR_DIRECTORY #Changing directory to your working directory
File=YOUR_FILENAME
if grep -q STRING_YOU_ARE_CHECKING_FOR "$File"; ##note the space after the string you are searching for
then
echo "Hooray!!It's available"
else
echo "Oops!!Not available"
fi
grep -q [PATTERN] [FILE] && echo $?
The exit status is 0 (true) if the pattern was found; otherwise blankstring.
if grep -q [string] [filename]
then
[whatever action]
fi
Example
if grep -q 'my cat is in a tree' /tmp/cat.txt
then
mkdir cat
fi
In case you want to checkif the string matches the whole line and if it is a fixed string, You can do it this way
grep -Fxq [String] [filePath]
example
searchString="Hello World"
file="./test.log"
if grep -Fxq "$searchString" $file
then
echo "String found in $file"
else
echo "String not found in $file"
fi
From the man file:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of
which is to be matched.
(-F is specified by POSIX.)
-x, --line-regexp
Select only those matches that exactly match the whole line. (-x is specified by
POSIX.)
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero
status if any match is
found, even if an error was detected. Also see the -s or --no-messages
option. (-q is specified by
POSIX.)
Try this:
if [[ $(grep "SomeString" $File) ]] ; then
echo "Found"
else
echo "Not Found"
fi
I done this, seems to work fine
if grep $SearchTerm $FileToSearch; then
echo "$SearchTerm found OK"
else
echo "$SearchTerm not found"
fi
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"

validate a string and make sure that it consists of specific characters

trying to validate a string at command line. each character should be among A-Z, a-z, 0-9 , special char(comma, underscore, period). If there are any other characters, display "invalid" else valid"
eg:
echo "hello123.txt" returns "valid"
echo "hello?.txt" returns "invalid"
echo "HEllo_hello" returns "valid"
Thank you.
If you have a suitable version of grep, you can use grep -v to determine this:
echo "test" | grep -v "^[A-Za-z0-9,_.]*$" > /dev/null
echo $? # 1
echo "#test" | grep -v "^[A-Za-z0-9,_.]*$" > /dev/null
echo $? # 0
In bash, you can use pattern matching on the right hand side of the == operator in [[ ... ]]:
#!/bin/bash
for string in 'hello123.txt' 'hello?.txt' 'HEllo_hello' ; do
if [[ $string == +([A-Za-z0-9,_.]) ]] ; then
echo valid
else
echo invalid
fi
done
You could create a script such as:
#!/bin/bash
if [[ $1 = "" ]] ; then
echo "Please run the following command with a string at the end...\
Example= ./script.bash testing"
exit 2
echo "$1" | grep -qi "^[a-z0-9.,_]*$"
if [[ $? = "0" ]] ; then
echo "Valid"
else
echo "Invalid"
fi
exit 0

Linux: using grep to find a word in a file then printing if it does or does not have that word in the file

I am trying to use the grep command however i do not know how to continue after the "grep $word $file" or even if that will work. What i need to do is get the program so that after they have typed in a word and a file if the word is in the file the program echo's "The word you have entered is in the file you have entered." and i also need it to print "I am sorry but the word you have entered is not in the file you have entered" if you can help it would be really helpful thank you
#!/bin/bash
echo "Welcome what please type in what you would like to do!"
echo "You can:"
echo "Search for words in file type (S)"
echo "Quit (Q)"
read option
while $option in
do
S) echo "What is the name of the file you would like to search for?"
read file
echo "What word would you like to find in the file?"
read word
grep $word $file
Q) echo "Goodbye!"
exit
esac
done
Use grep -q option to disable printing of the matching words and use echo $? to get the return value of grep. 0 is the return value if match found else 1 will be returned.
#!/bin/bash
echo "Welcome what please type in what you would like to do!"
echo "You can:"
echo "Search for words in file type (S)"
echo "Quit (Q)"
read option
case $option in
S) echo "What is the name of the file you would like to search for?"
read file
echo "What word would you like to find in the file?"
read word
grep -q $word $file
if [ $? -eq 0 ]; then
echo "$word found in $file"
else
echo "$word NOT found in $file"
fi
;;
Q) echo "Goodbye!"
exit
esac
Also you can use grep -w in case you want to match whole word. So your grep will look like
grep -wq $word $file
if [ $? -eq 0 ]; then
echo "$word found in $file"
else
echo "$word NOT found in $file"
Simple one liner using && and ||
grep -q $word $file && echo "found the word" || echo "not found the word"
eg
$ echo hello | grep -q hell && echo "found the word" || echo "not found the word"
found the word
$ echo hello | grep -q help && echo "found the word" || echo "not found the word"
not found the word

String not matching in shell script

I am trying to match two strings (IpAddress) as below. But it's not matching.
i=192.168.2.29
ipCheckInConfig="SG_1=192.168.2.24,192.168.2.29
> SG_2=192.168.2.20,192.168.2.23,192.168.2.31"
if echo "$i" | egrep -q "$ipCheckInConfig" ; then
echo "Matched"
else
echo "Not Matched"
fi
Could someone please help?
You don't need to call egrep for that. Use bash's internal regex capabilities:
if [[ "$ipCheckInConfig" =~ $i ]]; then
echo "Matched"
else
echo "Not Matched"
fi

Grep .html Syntax

I'm very new to bash so I apologize if this is a dumb question.
I'm trying to write a script that takes a file and tests to see if it ends in html. Here is my code:
echo tester.html | grep -E '[^ ]*[.html]'
Yet it echos every input I give it, how do I fix it?
echo tester.html | grep -q '\.html$' && echo "MATCH" || echo >&2 "NO MATCH"
or in bash
x=tester.html
[[ $x == *html ]] && echo "MATCH" || echo >&2 "NO MATCH"
&& & || boolean syntax is a shorcut for if condition; then something; else something_else; fi, see http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
NOTE
- using [] in a regex means character class (a set of characters)
I've solved it with the help of sputnick.
Here it is:
echo tester.html | grep -E *html
and this works,
thanks all.

Resources