Consider there is a variable line and variable word:
line = 1234 abc xyz 5678
word = 1234
The value of these variables are read from 2 different files.
I want to print the line if it contains the word. How do I do this using shell script? I tried all the suggested solutions given in previous questions. For example, the following code always passed even if the word was not in the line.
if [ "$line"==*"$word"*]; then
No need for an
if statement; just use
echo $line | grep "\b$word\b"
You can use
if [[ "$line" == *"$word"* ]]
Also you need to use the following to assign variables
line="1234 abc xyz 5678"
Working example --
Watch the white spaces!
When you set a variable to a value, don't put white spaces around the equal sign. Also use quotes when your value has spaced in it:
line="1234 abc xyz 5678" # Must have quotation marks
word=1234 # Quotation marks are optional
When you use comparisons, you must leave white space around the brackets and the comparison sign:
if [[ $line == *$word* ]]; then
Note that double square brackets. If you are doing pattern matching, you must use the double square brackets and not the single square brackets. The double square brackets mean you're doing a pattern match operation when you use
=. If you use single square brackets:
if [ "$line" = *"$word"* ]
You're doing equality. Note that double square brackets don't need quotation marks while single brackets it is required in most situations.
echo $line | grep "$word"
would be the typical way to do this in a script, of course it does cost a new process
You can use the bash match operator
[[ "$line" =~ "$word" ]] && echo "$line"
Don't forget quotes, as stated in previous answers (especially the one of @Bill).
The reason that
if [ "$line"==*"$word"* ] does not work as you expect is perhaps a bit obscure. Assuming that no files exist that cause the glob to expand, then you are merely testing that the string
1234 abc xyz 5678==*1234* is non empty. Clearly, that is not an empty string, so the condition is always true. You need to put whitespace around your
== operator, but that will not work because you are now testing if the string
1234 abc xyz 5678 is the same as the string to which the glob
*1234* expands, so it will be true only if a file named
1234 abc xyz 5678 exists in the current working directory of the process executing the shell script. There are shell extensions that allow this sort of comparison, but
grep works well, or you can use a case statement:
case "$line" in
*$word*) echo $line;;
An alternative solution would be using loop:
for w in $line
if [ "$w" == "$word" ]; then
if [ $a -eq $b ]