amar
amar

Reputation: 499

Execute a cat command within a sed command in Linux

I have a file.txt that has some content. I want to search for a string in file1.txt, if that string is matched I want to replace that string with the content of the file.txt. How can I achieve this?

I have tried using sed:

sed -e 's/%d/cat file.txt/g' file1.txt

This is searching for the matching string in the file1.txt and replacing that with the string cat file.txt, but I want contents of file.txt instead.

Upvotes: 12

Views: 32436

Answers (4)

torbatamas
torbatamas

Reputation: 1296

the e flag for s command does the trick: you can execute shell command in the second part of a s(ubstitue) command:

sed 's/%d/cat file1.txt/e'

https://www.gnu.org/software/sed/manual/sed.html#The-_0022s_0022-Command

If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output.

Upvotes: 1

skofgar
skofgar

Reputation: 1617

Given original.txt with content:

this is some text that needs replacement

and replacement.txt with content:

no changes

I'm not sure what your replacement criteria is, but lets say I want to replace all occurrences of the word replacement in the original file, you may replace the content of the original text with the content of the other file using:

> sed -e 's/replacement/'"`cat replacement.txt`"'/g' original.txt
this is some text that needs no changes

Upvotes: 3

Ivan Kolmychek
Ivan Kolmychek

Reputation: 1271

How about saving the content of the file in the variable before inserting it into sed string?

$content=`cat file.txt`; sed "s/%d/${content}/g file1.txt"

Upvotes: 6

Jonathan Leffler
Jonathan Leffler

Reputation: 754530

You can read a file with sed using the r command. However, that is a line-based operation, which may not be what you're after.

sed '/%d/r file1.txt'

The read occurs at the end of the 'per-line' cycle.

Upvotes: 2

Related Questions