Bash Shell Script Needs a Variable Passed with Characters "Escaped"

This script works if my variable: oo_line4 does not contain characters needing to be escaped. But not otherwise e.g. with oo_line4 as shown.

Is there a way to pass my variable: oo_line4 and have escape characters added by the Bash shell automatically? Or does this need a separate command/s?

These are the characters I need to escape: ([!"$&'()*,:;<=>?@[]^`{|}])

At the risk of suggesting something which is possibly simplistic… would it work if you used fgrep instead of egrep?

I'm wondering if the parentheses are throwing off egrep in your example.

Sorry if I'm missing something (it's been a long day/week/life).

1 Like

Good suggestion tj. I think this would work in this instance.

Still interested in my OP question for other Bash script cases if anyone has an answer. Thanks.

Hey Steve,

You can find a literal string using the -F switch in grep.

But @CJK shows a nifty way of quoting a string below.


Find Literal Text with Grep -- NOT a Regular Expression.kmmacros (4.7 KB)

1 Like

I think @ccstone's solution is the best and simplest in this particular case. In more general situations you might try this:

grep -E "$(printf '%q' "$KMVAR_oo_line4")" ./Existing_Book_Split_Files.txt

The two key elements here are the use of grep -E which has superseded the deprecated egrep; and the printf command which has %q token that will escape basically every character that isn't a letter or number (the exact details are likely found on man printf, but essentially, it'll do what you need in a bash-shell context).