Tech Support > Operating Systems > Linux / Variants > Sed, insert a file current line
Sed, insert a file current line
Posted by * Tong * on November 20th, 2003


Hi,

It is quite easy to include/append a file after a criteria line in sed by

'/criteria/ r file'

command. But is it possible to insert a file before a criteria line in
sed? If not, is there another simple tool (not perl) that can do it?

Thanks


--
Tong (remove underscore(s) to reply)
*niX Power Tools Project: http://xpt.sourceforge.net/
- All free contribution & collection

Posted by Robert Katz on November 20th, 2003


* Tong * wrote:

awk '{if (/criteria/) system("cat file"); print}'

--
Regards,

---Robert


Posted by rakesh sharma on November 20th, 2003


* Tong * <sun_tong@users.sourceforge.net> wrote in message news:<292fd8a71b89d833cc53eb5191e5e726@news.terane ws.com>...
sed -e '
/criteria/{
x;p
r file
x
}
h
' yourfile

note: this is not thoroughly tested as consecutive /criteria/ lines
will misbehave.

Posted by Tapani Tarvainen on November 20th, 2003


* Tong * <sun_tong@users.sourceforge.net> writes:

The 'r' command actually outputs the file just before reading
a new line to the pattern buffer (or at EOF). That can be forced
in mid-script by 'n' or 'N', and while 'n' will also print the
buffer before 'r' does its thing, 'N' won't, so:

sed -e '/criteria/{r file' -e N -e '}'

or if criteria is a regexp (not line number), also

sed -e '/criteria/r file' -e //N

Those will fail if /criteria/ occurs twice in a row.
That is easily fixed if needed, however, just print only the
matched /criteria/ line and reprocess the newly read line:

sed -e '/criteria/{r file' -e 'N;P;D' -e '}'

Warning: If /criteria/ occurs on the very last line of the file,
all of the above will fail with some sed versions, namely those
that discard the pattern buffer if 'N' is executed at the last line.
Gnu sed is safe, with others you should test for that before
relying on these, unless you know /criteria/ cannot occur on the
last line. The only obvious workaround for such broken sed's is
appending a dummy line before the sed call and then deleting it:

(cat infile; echo) |
sed -e '$d' -e '/criteria/{r file' -e 'N;P;D' -e '}'

There are always alternative solutions in unix. E.g.,

awk '/criteria/{while (getline tmp <"file") print tmp} {print}'

or if criteria isn't a regexp,

while read line; do
case "$line" in *criteria*) cat file;; esac
printf "%s\n" "$line"
done <infile

--
Tapani Tarvainen