Ralph
Ralph

Reputation: 458

Using a file's content in sed's replacement string

I've spent hours searching and can't find a solution to this. I have a directory with over 1,000 PHP files. I need to replace some code in these files as follows:

Find:

session_register("CurWebsiteID");

Replace with (saved in replacement.txt:

if(!function_exists ("session_register") && isset($_SERVER["DOCUMENT_ROOT"])){require_once($_SERVER["DOCUMENT_ROOT"]."/libraries/phpruntime/php_legacy_session_functions.php");} session_register("CurWebsiteID");

Using the command below, I'm able to replace the pattern with $(cat replacement.txt) whereas I'm looking to replace them with the content of the text file.

Command being used:

find . -name "*.xml" | xargs -n 1 sed -i -e 's/mercy/$(cat replacement.txt)/g'

I've also tried using variables instead replacement=code_above; and running an adjusted version with $(echo $replacement) but that doesn't help either.

What is the correct way to achieve this?

Upvotes: 2

Views: 82

Answers (2)

SLePort
SLePort

Reputation: 15461

You don't need command substitution here. You can use the sed r command to insert file content and d to delete the line matching the pattern:

find . -name "*.xml" | xargs -n 1 sed -i -e '/mercy/r replacement.txt' -e '//d'

Upvotes: 5

codeforester
codeforester

Reputation: 42999

$(...) is not interpreted inside single quotes. Use double quotes:

find . -name "*.xml" | xargs -n 1 sed -i -e "s/mercy/$(cat replacement.txt)/g"

You can also do away with cat:

find . -name "*.xml" | xargs -n 1 sed -i -e "s/mercy/$(< replacement.txt)/g"

In case replacement.txt has a / in it, use a different delimiter in sed expression, for example @:

find . -name "*.xml" | xargs -n 1 sed -i -e "s@mercy@$(< replacement.txt)@g"

See also:

Upvotes: 2

Related Questions