How to Use Regex in a Shell Script Variable?

0
3
Asked By CuriousCat99 On

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

Answered By DebuggingDude On

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!

Answered By RegexGuru77 On

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.

Answered By ShellScripter42 On

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

Answered By BashNinja101 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.