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
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
bazthen
$ echo "include(file.txt)" | sed -E 's:include\(([^)]+)\):cat /tmp/\1:e'
foo bar
bazor (not sure why you need readlink here)
$ echo "include(file.txt)" | sed -E 's:include\(([^)]+)\):cat "$(readlink -f "/tmp/\1")":e'
foo bar
bazNote 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").