kishorer747
kishorer747

Reputation: 820

How to use variable names when grep and sed are combined?

I want to search for a string and replace it with different string in all files in a directory recursively. I am able to use sed on one file like this and it works:

sed -i "s|${searchStr}|${replaceStr}|g" "${rootDir}"file.cs

But when I am using it with grep, i am not seeing the changes in the files or getting any error messages.

This Works:

grep -rnlis --include=*.{html,css,js,aspx} './' -e "/images/" |
 xargs -i@ sed -i "s|/images/|https://example.com/Images/|I" @

Tried these but did not work:

searchStr='/images/'
replaceStr='https://example.com/Images/'
...  -e "$searchStr" | xargs -i@ sed -i "s|$searchStr|$replaceStr|I" @

and

...  -e "${searchStr}" | xargs -i@ sed -i "s|${searchStr}|${replaceStr}|I" @

Error Messages when used with Variable Names in the expression:

: No such file or directoryult.js

: No such file or directoryders.aspx

: No such file or directoryork.css

: No such file or directoryal-power.js

How do I use variables names instead of hardcoding?

Environment: cygwin (so Windows GNU sed /grep)

Upvotes: 4

Views: 900

Answers (1)

kishorer747
kishorer747

Reputation: 820

Thanks to @NeronLeVelu, here is the solution:

searchStr='/images/' replaceStr='https://example.com/Images/' grep -rnlis --include=*.{html,css,js,aspx} "$rootDir" -e "/images/" | while read File; do sed -i "s|${searchStr}|${replaceStr}|I" "${File}"; done

It works perfectly and replacing the searchStr in rootDir recursively.

Upvotes: 1

Related Questions