开发者

Grep command being reversed by special character?

开发者 https://www.devze.com 2023-04-10 18:20 出处:网络
I am trying to write a bash script which will search through a txt file for a string from another txt file which is stored within a variable.However the string has a number of special characters in it

I am trying to write a bash script which will search through a txt file for a string from another txt file which is stored within a variable. However the string has a number of special characters in it and for some reason it seems to be corrupting the grep command. The string is the following: Sometxt ^/someurl/?$ http开发者_StackOverflow://somewebsite.com/

the grep command I'm using is

grep -v "$string" file.txt >> new_file.txt

This doesn't seem to work and if I echo the actual grep command using:

echo "grep -v \"$string\" file.txt >> new_file.txt"

I get an output that is all jumbled up.

If I enter the grep command manual and enter the actual string it works fine so I'm assuming that my shell is trying to expand the special characters but I don't how to escape all of them within the string.

Anyone have any ideas?

Thanks.


try fgrep (or grep -F)

By default grep interprets the search pattern as a basic regular expression, giving special meaning to characters like ., $, ^ [] etc


Untested, but this might help

grep -v "$(printf "%q" "$string")" file.txt >> new_file.txt

The bash builtin printf %q formatter escapes shell special characters.

0

精彩评论

暂无评论...
验证码 换一张
取 消