Re: Insert the content of a file (with command r?)

Davide Brini <[email protected]>
Newsgroups gmane.editors.sed.user
Message-ID <[email protected]>
On Tue, 24 Jul 2012 13:23:41 -0500, Tim Chase <[email protected]> wrote:

> On 07/24/12 05:05, Laurent Le Brun wrote:
> > I'd like to insert the content of a file when the input matches some
> > regexp. It tried this simple script: /regexp/r file.txt
> > It works fine, except that it's inserting the content of the file
> > after the line matching the regexp. I'd like to insert it BEFORE
> > instead.
> 
> I played around with this and am not sure whether I've found an odd
> bug in GNU sed (4.2.1 on Debian stable).  I tried holding the match,
> reading the file, then printing out the held match, and it seems to
> do all the reading at the end of a cycle:
> 
>   ============insert.sed==============
>   /regexp/{
>   h       # hold the existing pattern
>   s/.*//  # delete the existing match
>   # read in the file
>   r file.txt
>   g       # return the text we held
>   }
>   ====================================
> 
> I used "4" for my regex and piped the output of "seq 10" into it to
> insert the file.txt before the "4" line. The "4" still comes out
> before the contents of file.txt does.

The command "r" just schedules the file for reading at the end of the
cycle. Here's the standard:

"The a and r commands schedule text for later output. The text specified
for the a command, and the contents of the file specified for the r
command, shall be written to standard output just before the next attempt
to fetch a line of input when executing the N or n commands, or when
reaching the end of the script. If written when reaching the end of the
script, and the -n option was not specified, the text shall be written
after copying the pattern space to standard output. The contents of the
file specified for the r command shall be as of the time the output is
written, not the time the r command is applied. The text shall be output in
the order in which the a and r commands were applied to the input."

As for the OP's problem, this should work, assuming the pattern never
occurs on the very last line of the file:

/pattern/ {
  r file.txt
  N
}

Given the way "r" works, I'm not sure there's even a way to insert the file
before the last line of the file with sed only. In that case, one can
perhaps use dirty shell tricks, like eg

{ cat input.txt; echo; } | sed program.sed | head -n -1




-- 
D.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.