- 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
- how to read a file line by line and store it into string array using WIN32 programming? (Development Resources) by shivaraj
- Macro to cause Explorer to open in same file path location that current file is located. (Microsoft Windows) by cparnell@southernstorefixtures.com
- Email template insert data fields into subject line. (Windows CRM) by Steve
- Office Application (Insert Name) has not been installed for the current user (Home and office) by Keith Dahl
- insert new line in 100 text files (Software & Applications) by Jan2004

