[GLLUG] Replacing newlines in text file

Tom Taylor tom at tommyt.co.uk
Sun Aug 30 10:03:05 UTC 2015


Another option is perl ...

perl -pi -e 's/(.)\n$/$1/ ; s/\n/\n\n/' /tmp/test

The first regex will remove any single newlines that are not at the start
of the line and the second will double any remaining ones.

If you want to see the output before writing to the file, remove the i.

Tom

On 30 August 2015 at 10:55, Andy Smith <andy at bitfolk.com> wrote:

> Hi Dylan,
>
> On Sun, Aug 30, 2015 at 10:37:54AM +0100, Dylan wrote:
> > I have a text file with 'hard' newlines at the end of each 'line'
> > (often mid-sentence,) and multiple newlines at the end of paragraphs.
> > I need a simple incantation to change all occurrences of a *single*
> > newline to a space, and leave the multiple newlines in place.
>
> You probably want something based on sed, e.g. from
>
> http://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed
>
>     sed ':a;N;$!ba;s/\n/ /' source.txt > dest.txt
>
> If you just wanted to replace every single newline with a space than
> tr would be much simpler:
>
>     tr '\n' ' '
>
> But that doesn't appear to be what you asked for (you asked for only
> the first newline).
>
> The invocation of sed is more complicated because sed is
> line-oriented.
>
> Cheers,
> Andy
>
> --
> http://bitfolk.com/ -- No-nonsense VPS hosting
>
> _______________________________________________
> GLLUG mailing list
> GLLUG at mailman.lug.org.uk
> https://mailman.lug.org.uk/mailman/listinfo/gllug
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.lug.org.uk/pipermail/gllug/attachments/20150830/1a6639fc/attachment.html>


More information about the GLLUG mailing list