I'm having trouble passing a regex pattern as a variable in my shell script. I have a text file with various strings that match a specific format, like this:
[ECO "B40"]
[ECO "E61"]
[ECO "E63"]
When I run the grep command like this:
grep "\"E[6-9][0-9]\"" testdbs/testdb.pgn
it successfully finds all the ECO codes from E60 to E99. However, when I try to pass the same regex to my script with this command:
./script.sh --eco ""E[6-9][0-9]"" --input testdbs/testdb.pgn
it fails. The script correctly gets the --eco flag through a getopts loop, but when I try to use this regex later in my script like this:
while IFS= read -r line; do
if [[ "$line" =~ ^"$ecoregex" ]]; then
ecomatches="true"
fi
done < $inputfile
it doesn't match any lines. Can anyone help figure out what I'm missing?
4 Answers
Just a heads-up about the caret (^) in your regex. It forces the match to happen at the start of the line. If your ECO format doesn't start right there, it won't match. It might work better without it. Also, consider posting a minimal version of your script to help others replicate your issue easily!
Escaping can get tricky in bash. I suggest using single quotes for the outer string and keeping the inner double quotes as is, like this:
./script.sh --eco '"E[6-9][0-9]"' --input testdbs/testdb.pgn
This way, bash will handle it better without needing so many escapes.
It looks like the quotes around your regex are the issue. In a bash `[[ ... ]]` condition, enclosing the regex in quotes treats it as a plain string. Try removing the quotes from your regex:
if [[ "$line" =~ $ecoregex ]]; then
ecomatches="true"
fi
A few tips:
1. Avoid putting `.sh` on your script names; it's not necessary and can confuse some systems.
2. Use single quotes around your regex, like so: `'"E[6-9][0-9]"'`.
3. When reading the regex in a loop, use `"$@"` instead of `"$*"` for better argument handling.
Checking these might help debug your script!
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String