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?
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.
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.
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.
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.
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
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.
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
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