Search code examples
regexgrepescaping

Using grep to find all strings (with %) in files recursively


To find all occurrences of printf in all files recursively:

grep -rnw ~/bin/ -e "printf"

However, how to escape the search pattern printf '%0?

I failed in the following trials to escape the percentage sign:

grep -rnw ~/bin/ -e "printf '%0"

grep -rnw ~/bin/ -e "printf \'\%0"

grep -rnw ~/bin/ -e "printf \'%%0"

Sample file:

#!/bin/sh

printf '%04d' "$var"

Solution

  • It's not working because you used the -w option, which only matches whole words. In your file, %0 is the beginning of the word %04d. Since there's no word boundary after %0, it doesn't match.

    Get rid of the -w option and it will match. However, it will also match

    fprintf '%04d' "$var"
    

    Since you want to match a word boundary before printf, use the \b word boundary pattern.

    grep -rn ~/bin/ -e "\\bprintf '%0"