0

I am having many text file with different directories. I need to search one specific string and I need to replace the string with the specific value as $test. I need to search the all files in all directories, for this.

Example: In one file there is a string as abcd, I need to replace the string abcd as $test. I have a script that is searching the string in all files and replacing the string. But I can't able to replace the string with $ symbol. Below script is working without $.

command="find \`pwd\` -name \"*\" -type f -exec grep -l \"abcd\" {} \\; 2>/dev/null | xargs  perl -pi.bak1 -w -e 's/abcd/test/g;'"

Below script is not working with $ symbol.

command="find \`pwd\` -name \"*\" -type f -exec grep -l \"abcd\" {} \\; 2>/dev/null | xargs  perl -pi.bak1 -w -e 's/abcd/\$test/g;'"

How to replace the string abcd to $test.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
palani
  • 1

1 Answers1

2

Don't try to put commands in variables (see e.g. "How can we run a command stored in a variable?").

Your command is having issues with the $ because Perl uses it on its scalar variables. You would have to escape it not only from the shell, but from Perl as well (\\\$).

To replace abcd with $test in all files in or below the current directory using find and GNU or BSD sed, use

find . -type f \
    -exec grep -qF 'abcd' {} ';' \
    -exec sed -i.bak 's/abcd/$test/g' {} ';'

This will find all regular files, test whether the string exists in the file, and if it does, replace it with the string $test (creating a backup of the original file with the suffix .bak).

The same thing, but using Perl:

find . -type f \
    -exec grep -qF 'abcd' {} ';' \
    -exec perl -pi.bak -e 's/abcd/$test/g' {} ';'

If you remove the -exec grep part, you will get backup files for all files, even though they may not have contained the string abcd.

Kusalananda
  • 333,661