0

I would like to search a file line by line and print out a given message to the screen when a string is matched and a different message to the screen when the string isn't matched.

This is what I have so far:

A file called network.txt that is located in the same directory that the script is running from. This is the contents of the file:

am.12345
XXXXXXXX
am.67890
XXXXXXXX

This is the script:

#!/bin/bash
file="network.txt"
for line in `cat $file`
  do
    if [ $line == am.* ]
      then
         echo $line
    elif [ $line != am.* ]
      then
         echo "We couldn't find what you were looking for"
    fi
done

This is the output I receive from the bash debug:

+ file=network.txt
++ cat network.txt
+ for line in '`cat $file`'
+ '[' am.12345 == 'am.*' ']'
+ '[' am.12345 '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for
+ for line in '`cat $file`'
+ '[' XXXXXXXX == 'am.*' ']'
+ '[' XXXXXXXX '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for
+ for line in '`cat $file`'
+ '[' am.67890 == 'am.*' ']'
+ '[' am.67890 '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for
+ for line in '`cat $file`'
+ '[' XXXXXXXX == 'am.*' ']'
+ '[' XXXXXXXX '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for

But when I run the script, I don't get the expected behaviour:

macbook:~ enduser$ ./network.sh
We couldn't find what you were looking for
We couldn't find what you were looking for
We couldn't find what you were looking for
We couldn't find what you were looking for

I believe the output should look like this:

am.12345
We couldn't find what you were looking for
am.67890
We couldn't find what you were looking for

What do I need to change to fix this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ARL
  • 986
  • 2
  • 12
  • 25

1 Answers1

0

You need to use [[ $line =~ am.* ]].

Smart-matching, or regular expression comparison, uses the Perl =~ operator, not == as you have it coded. RTFM for details. (Search for =~.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aghast
  • 14,785
  • 3
  • 24
  • 56