ramgorur
ramgorur

Reputation: 2164

bash: how to check if a string starts with '#'?

In bash I need to check if a string starts with '#' sign. How do I do that?

This is my take --

if [[ $line =~ '#*' ]]; then
    echo "$line starts with #" ;
fi

I want to run this script over a file, the file looks like this --

03930
#90329
43929
#39839

and this is my script --

while read line ; do
    if [[ $line =~ '#*' ]]; then
        echo "$line starts with #" ;
    fi
done < data.in

and this is my expected output --

#90329 starts with #
#39839 starts with #

But I could not make it work, any idea?

Upvotes: 28

Views: 52810

Answers (4)

Kris
Kris

Reputation: 4823

If you additionally to the accepted answer want to allow whitespaces in front of the '#' you can use

if [[ $line =~ ^[[:space:]]*#.* ]]; then
    echo "$line starts with #"
fi

With this

#Both lines
    #are comments

Upvotes: 6

anubhava
anubhava

Reputation: 785058

Just use shell glob using ==:

line='#foo'
[[ "$line" == "#"* ]] && echo "$line starts with #"
#foo starts with #

It is important to keep # quoted to stop shell trying to interpret as comment.

Upvotes: 6

eLemEnt
eLemEnt

Reputation: 1801

while read line ; 
do
    if [[ $line =~ ^#+ ]]; then
        echo "$line starts with #" ;
    fi
done < data.in

This will do the trick remove * with + + matches 1 or more while * matches 0 or more so in your code it will show number even if it does not start with '#'

Upvotes: 1

choroba
choroba

Reputation: 241828

No regular expression needed, a pattern is enough

if [[ $line = \#* ]] ; then
    echo "$line starts with #"
fi

Or, you can use parameter expansion:

if [[ ${line:0:1} = \# ]] ; then
    echo "$line starts with #"
fi

Upvotes: 48

Related Questions