Linux – Help with SED command to replace text in several files

debianlinuxsed

EDIT: I found the solution. This command works, in case someone finds it useful. The i.bak modifier makes a backup of every changed file.

find /pathoffilestochange -name "*.php" | xargs sed 's|/wrong/path/|/correct/path/|g'

Hello,

I want to change a path inside dozens of .php files. I dont know how to use sed, but I got this command somewhere on the internet before and have succesfully used it.

 find /ruta -name "*.txt" | xargs sed -i.bak 's/charset=Foo/Bar/g'

Except now I need to change the delimiters to a different character, hece the @. This is my current command:

find /pathoffilestochange  -name "*.php" | xargs sed -i.bak 's@charset=/wrong/path/@/correct/path/@g'

It is not working, and it doesnt give any errors, but I check the files and they remain the same.

I am executing the command as root, which is the file owner, and the permissions seem to be OK, so that must not be the issue. I am running Debian.

Best Answer

Just replacing the reserved delimiter with @ won't work. What you have to do is to escape your slashes like this \/ With the \ character, you cancel the special meaning of a character in a regular expression.

So, your command needs to look like this:

find /pathoffilestochange -name "*.php" | xargs sed -i.bak \ 's/charset=\/wrong\/path\//\/correct\/path\//g'

It's confusing, but that's how regexes are working.

By the way, with the single backslash after -i.bak I canceled the meaning of the new line character, so I could this command on two lines for easier readability.

Related Topic