I am learning Regular expression for bash scripting. However, when I was testing string match, the lines always can't pass. Here is what I am testing:
I have a txt file contains a list of "songs":
$ cat soundtrack.txt
Ludwig Van Beethoven - 01 - Allero.oog
Ludwig Van Beethoven - 02 - Adag.mp3
Ludwig Van Beethoven - 03 - Beach.oog
Ludwig Van Beethoven - 04 - Caven Adven.wmv
I would like to use Regex to get the "track number" which are the numerical ones.
Here's the script:
$ cat soundtrack.sh
#!/bin/bash
IFS=$'\n'
for CD in `cat soundtrack.txt`
do
if [[ "$CD" =~ "([[:alpha:][:blank:]]*)- ([[:digit:]]*) - (.*)$" ]]
then
echo "Found ${BASH_REMATCH[2]}"
fi
done
However, the bash debug shows the string was unable to match the regex:
$ bash -x soundtrack.sh
+ IFS='
'
++ cat soundtrack.txt
+ for CD in '`cat soundtrack.txt`'
+ [[ Ludwig Van Beethoven - 01 - Allero.oog =~ \(\[\[:alpha:]\[:blank:]]\*\)- \(\[\[:digit:]]\*\) - \(\.\*\)\$ ]]
+ for CD in '`cat soundtrack.txt`'
+ [[ Ludwig Van Beethoven - 02 - Adag.mp3 =~ \(\[\[:alpha:]\[:blank:]]\*\)- \(\[\[:digit:]]\*\) - \(\.\*\)\$ ]]
+ for CD in '`cat soundtrack.txt`'
+ [[ Ludwig Van Beethoven - 03 - Beach.oog =~ \(\[\[:alpha:]\[:blank:]]\*\)- \(\[\[:digit:]]\*\) - \(\.\*\)\$ ]]
+ for CD in '`cat soundtrack.txt`'
+ [[ Ludwig Van Beethoven - 04 - Caven Adven.wmv =~ \(\[\[:alpha:]\[:blank:]]\*\)- \(\[\[:digit:]]\*\) - \(\.\*\)\$ ]]
But, if I test directly in the shell with the same expression, it works:
$ if [[ "Ludwig Van Beethoven - 01 - Allero.oog" =~ ([[:alpha:][:blank:]]*)-\ ([[:digit:]]*)\ -\ (.*)$ ]]; then echo yes; else echo no; fi
yes
What's wrong with my script? Do I have to add extra quotas or backslashes? Just doesn't make sense to me.
P.S.
$ bash --version
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)