I can't seem to figure out how to write a regex correctly in an if statement. I wanted it to print out all the lines with "End Date" in it.
NUMBERS contains a text file with the following content:
End Date ABC ABC ABC ABC ABC ABC
05/15/13 2 7 1 1 4 5
04/16/13 4 3 0 1 3 6
03/17/13 6 9 3 8 5 9
02/18/13 8 2 7 1 0 1
01/19/13 1 9 2 2 5 2
12/20/12 7 2 7 1 0 1
Here is a snippet of my code that I am having problems with:
if [ -f $NUMBERS ]
then
while read line
do
if [ $line = ^End ]
then
echo "$line"
else
echo "BROKEN!"
break
fi
done < $NUMBERS
else
echo "===== $NUMBERS failed to read ====="
fi
The output is:
Broken!
Conditions in Shell ScriptsAn if-else statement allows you to execute iterative conditional statements in your code. We use if-else in shell scripts when we wish to evaluate a condition, then decide to execute one set between two or more sets of statements using the result.
A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.
You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.
A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.
if you're using bash, try =~
:
...
if [[ $line =~ ^End ]]
Note that the following will NOT work:1
if [[ "$line" =~ "^End" ]]
The portable solution is to use case
which supports wildcards (glob wildcards; not actual regular expressions) out if the box. The syntax is slightly freaky, but you get used to it.
while read -r line; do
case $line in
End*) ... your stuff here
... more your stuff here
;; # double semicolon closes branch
esac
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With