0

I tried the following code, but it doesn't do what I want:

echo "include(file.txt)" | sed -E 's/include\(([^)]+)\)/'$(cat $(readlink -f /tmp/$1))'/g'

I need replace some special words with file content. This is similar "include" function of the PHP.

1 Answer 1

2

With GNU sed, you can use the e modifier to execute the replacement pattern after substitution:

e

This command allows one to pipe input from a shell command into pattern space. If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output. A trailing newline is suppressed; results are undefined if the command to be executed contains a NUL character. This is a GNU sed extension.

Ex. given

$ cat /tmp/file.txt
foo bar
baz

then

$ echo "include(file.txt)" | sed -E 's:include\(([^)]+)\):cat /tmp/\1:e'
foo bar
baz

or (not sure why you need readlink here)

$ echo "include(file.txt)" | sed -E 's:include\(([^)]+)\):cat "$(readlink -f "/tmp/\1")":e'
foo bar
baz

Note that it is the whole pattern space resulting from the successful substitution that is executed, and that it is executed by /bin/sh (so you need to avoid "bashisms").

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .