user978206
user978206

Reputation: 31

Grep command being reversed by special character?

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://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.

Upvotes: 3

Views: 862

Answers (2)

glenn jackman
glenn jackman

Reputation: 246847

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.

Upvotes: 1

sehe
sehe

Reputation: 393114

try fgrep (or grep -F)

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

Upvotes: 5

Related Questions