[plug] A sed question?

Alastair Irvine alastair at al.id.au
Mon Jan 4 09:42:25 WST 2010

On Wed, 21 Oct 2009 03:32 pm, Arie Hol wrote:
> Is there a way of using sed to insert a 'backpsace' character ?
> I know how to use sed to insert  'tabspace' and 'newline'
> characters, but I can't figure out how to insert a 'backspace'
> character.
> 'man sed'     and 'info sed'  don't hold any enlightehment for
> me.
> Online manuals have not shed any light for me either.
> I need this functionality so that I can process the output from a
> series of grep commands which are piped through 'sort' and 'uniq'
> into a data file - but there are many instances where I want/need
> to append one line of the data file to the end of the previous
> line.

When you face this kind of problem, it is important to realise that 
sed operates on an "input; process; output" model.  You can't look 
back in history as past lines have already been output (or 
printed).  Also, sed deals with input on a line-by-line basis, so 
you don't normally get to see the newline character.  

> Is this possible using sed ???????

To solve the "I need to append the next line" problem, you need to 
think in terms of "peeking into the future".

The solution is actually fairly neat.  (Unlike in a regular 
programming language, you don't need to keep track of state using 
variables.)  The way it is done is by using the N command
- from the sed manual (/usr/share/info/sed.info.gz i.e. "info sed"):
 "Add a newline to the pattern space, then append the next line of
  input to the pattern space."

(The pattern space is the place that sed keeps the current line of 
input until a command like 'p' is used to output it.)

The following sed program will join the next line onto the end of 
any line that has a FISH in it, replacing the newline with a comma:

  #! /bin/sed -f
  /FISH/ { N

The following sed command will remove all newlines in the input, 
replacing all input lines (except the first) with parenthesised 
strings.  (Using a label and the conditional jump command 't'.):
  sed -e :start -e N -e 's/\n\(.*\)/(\1)/' -e 't start'

[snip platform question]

Alastair Irvine, Warpspace IT <http://www.warpspace.net/>
Business enquiries: 1300 881744 or guru at warpspace.net
[Linux Counter user #404151; OpenDocument Format Alliance member]

More information about the plug mailing list