Diego
Diego

Reputation: 79

How to search with grep exactly string in a file via shell linux?

I have a file, the content of file has a string like this:

'/ad/e','@'.base64_decode("ZXZhbA==").'($zad)', 'add'

I want to check the file has this string. But when I use grep to check, It always return false. I try some ways:

grep "'/ad/e','@'.base64_decode("ZXZhbA==").'($zad)', 'add'" foo.txt

grep "'/ad/e','@'\.base64_decode\("ZXZhbA\=\="\)\.'\(\$zad\)', 'add'" foo.txt

str="'/ad/e','@'\.base64_decode\("ZXZhbA\=\="\)\.'\(\$zad\)', 'add'"

grep "$str" foo.txt

Can you help me? Maybe, another command line.

This is my case:

while read str; do
    if [ ! -z "$str" ]; then
        if grep -Fxq "$str" "$file_path"; then
            do somthing
        fi
    fi
done < <(cat /usr/local/caotoc/db.dat)

Thank you so much!

Upvotes: 1

Views: 348

Answers (2)

chepner
chepner

Reputation: 530872

First, you need to make sure the string is quoted properly. This is a bit of an art form, since your string contains both single and double quotes. One thought would be to use read and a here-document to avoid having to escape anything.

Second, you need to use -F to perform exact string matching instead of more general regular-expression matching.

IFS= read -r str <<'EOF'
'/ad/e','@'.base64_decode("ZXZhbA==").'($zad)', 'add'
EOF

grep -F "$str" foo.txt

Based on the update, you can use a simple loop to read them one at a time.

while IFS= read -r str; do
  grep -F "$str" foo.txt
done < /usr/local/caotoc/db.dat

You may be able to simply use the -f option to grep, which will cause grep to output lines from foo.txt that match any line from db.dat.

grep -f /usr/local/caotoc/db.dat -F foo.txt

Upvotes: 4

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

Instead of trying to workaround regexes, the simplest way is to turn off regular expressions using -F (or --fixed-strings) option, which makes grep act like a simple string search

-F, --fixed-strings PATTERN is a set of newline-separated strings

like this:

grep -F "'/ad/e','@'.base64_decode(\"ZXZhbA==\").'(\$zad)', 'add'" test

Note: because of the shell, you still need to escape:

  • double quotes
  • dollar sign or else $zad is evaluated as an environment variable

Upvotes: 3

Related Questions