Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

bash - How to escape a previously unknown string in regular expression?

I need to egrep a string that isn't known before runtime and that I'll get via shell variable (shell is bash, if that matters). Problem is, that string will contain special characters like braces, spaces, dots, slashes, and so on.

If I know the string I can escape the special characters one at a time, but how can I do that for the whole string?

Running the string through a sed script to prefix each special character with could be an idea, I still need to rtfm how such a script should be written. I don't know if there are other, better, options.

I did read re_format(7) but it seems there is no such thing like "take the whole next string as literal"...

EDIT: to avoid false positives, I should also add newline detection to the pattern, eg. egrep '^myunknownstring'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you need to embed the string into a larger expression, sed is how I would do it.

s_esc="$(echo "$s" | sed 's/[^-A-Za-z0-9_]/\&/g')" # backslash special characters
inv_ent="$(egrep "^item [0-9]+ desc $s_esc loc .+$" inventory_list)"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...