Bash script using sed with variables in a for loop?

I am trying to write a bash script that takes several variables and then does a search / replace with a given file search using grep to get a list of files with a string. I think the problem I am facing is seeing the variables in sed. I'm not sure what else could be.

if [ "$searchFiles" != "" -a "$oldString" != "" -a "$newString" != "" ]; then echo -en "Searching for '$searchFiles' and replacing '$oldString' with '$newString'.\n" for i in `grep $oldString $searchFiles |cut -d: -f1|uniq`; do sed -i 's/${oldString}/${newString}/g' $i; done echo -en "Done.\n" else usage fi 
+6
source share
2 answers

use double quotes so that the shell can replace variables.

 for i in `grep -l $oldString $searchFiles`; do sed -i "s/${oldString}/${newString}/g" $i; done 

if the search or replace string contains special characters, you need to avoid them: Reset the string for the sed replacement pattern

+16
source

Use double quotes so that environment variables expand by the shell before calling sed:

  sed -i "s/${oldString}/${newString}/g" $i; 

Be careful: if either oldString or newString contain slashes or other special regular expression characters, they will be interpreted as their special meaning, and not as literal strings.

+4
source

Source: https://habr.com/ru/post/894885/


All Articles