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.

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.

  • I tried perl -pi.bak1 -w -e "'s/comp/\$AH/g;'" not working – palani May 14 '18 at 19:43
  • @palani Same thing there, you will have to use \\\$. You do want to replace with the actual string $AH, right? Not with the value of the shell variable $AH? – Kusalananda May 14 '18 at 19:51
  • @palani See updated answer. – Kusalananda May 14 '18 at 19:53
  • you correct I need to replace the actual string as "$AH". – palani May 15 '18 at 10:39
  • @Kusalanda, thank you very much, issue resolved. – palani May 15 '18 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.