How to use variable names when combining grep and sed?

I want to find a line and replace it with another line in all files in the directory recursively. I can use sed in a single file like this, and it works:

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

But when I use it with grep, I do not see changes in the files and do not receive any error messages.

Working:

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

I tried, 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 an 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 to use variable names instead of hardcoding?

Environment: cygwin (so Windows GNU sed / grep)

+4
source share
1 answer

Thanks @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 great and recursively replaces searchStr with rootDir.

+1

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


All Articles