[Gllug] sed script for removing lone new line characters

Steve Nelson sanelson at gmail.com
Fri Mar 3 15:12:48 UTC 2006


On 3/3/06, Dan Stevens (IAmAI) <dan.stevens.iamai at gmail.com> wrote:
> Could anyone advise me on a sed script for removing lone new line
> characters, but not consecutive new lines of two or more?

sanelson at smyslov:~$ cat test
Delete this line:

Don't delete these lines:


Because there are > 1

sanelson at smyslov:~$ sed  '/^$/{N;/\n$/!D;}' < test
Delete this line:
Don't delete these lines:


Because there are > 1

How it works:

First we're interested in new lines, so search for newlines:

--> /^$/

Ok, once we match a new line - ie we have "nothing" in pattern space,
enter {}.  All commands enclosed in {} will be executed one by one.

Now we need to add the following line to pattern space - we do that
with N.  N will add the following line, inserting a literal \n.  This
produces line1\nline2.

--> N

Now, because we are matching on a blank line, which I will call
(nothing), after we append the following line, we have two
possibilities:

1) Pattern space contains: (nothing)\sometext
2) Pattern space contains (nothing)\(nothing)

The second case is what happens if we have more than one consecutive blank line.

Ok, so now lets check for this second case:

-->/\n$/

and also negate it - we are saying "If we do *not* match
(nothing)\(nothing), take action."

Now, if we do not match (nothing)\(nothing) this means that the
following line contained text.  This means that the line we matched
was on its own.

If this is the case delete it:

-->  D

S.
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list