Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Scripting: RegEx in if Statement

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!

like image 973
dalawh Avatar asked May 15 '13 23:05

dalawh


People also ask

Can we use if in shell script?

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.

What is bash if [- N?

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.

How do I check if a string matches in regex bash?

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.

What does =~ mean in shell?

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.


2 Answers

if you're using bash, try =~:

...
if [[ $line =~ ^End ]]

Note that the following will NOT work:1

if [[ "$line" =~ "^End" ]]
like image 114
datguy Avatar answered Oct 04 '22 07:10

datguy


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
like image 40
tripleee Avatar answered Oct 04 '22 07:10

tripleee