As others have said, you cannot use variables in a sed script, but you can "fake" it using additional leading input, which is added to your storage buffer. For instance:
[ ghoti@pc ~/tmp]$ cat scr.sed 1{;h;d;};/^--$/g [ ghoti@pc ~/tmp]$ sed -f scr.sed <(date '+%Y-%m-%d'; printf 'foo\n--\nbar\n') foo 2012-10-10 bar [ ghoti@pc ~/tmp]$
In this example, I use process redirection to get input to sed. "Important" data is generated by printf . Instead, you can write a file or run some other program. The "variable" is created by the date command and becomes the first line of script input.
The sed script command takes the first line, puts it in the sed storage buffer, and then deletes the line. Then, for any subsequent line, if it matches a double dash (our "macro replacement"), it replaces the contents of the hold buffer. And prints because this is the default sed action.
Holding buffers (g, g, h, H, and x commands) is an advanced gray programming. But once you understand how they work, they open up new dimensions for sed fu.
Note. This solution will only help you replace whole lines. Replacing substrings within strings may be possible using a hold buffer, but I cannot imagine how to do this.
(Another note: I am doing this on FreeBSD, which uses a different sed from what you find on Linux. This may work in GNU sed, or it may not be so: I have not tested it.)
source share