Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

bash

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?

like image 991
ramgorur Avatar asked Feb 14 '15 10:02

ramgorur


People also ask

What is $@ in Bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do I test a string in Bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

What does =~ mean in Bash?

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.

What is Echo $$ in Bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.


3 Answers

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 
like image 68
choroba Avatar answered Sep 24 '22 13:09

choroba


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.

like image 34
anubhava Avatar answered Sep 22 '22 13:09

anubhava


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
like image 27
Kris Avatar answered Sep 22 '22 13:09

Kris