shellunixsednewlinelf

Unix shell script to remove new lines preceded with specific characters


First, thanks in advance for your helps.

I need to replace new lines (\n) by a space in an unix files when they are not preceded with ';'.

For example, if you have in an unix file something like :

TestFields;TestFields2
;TestFields3;TestFields4

The output should be :

TestFields;TestFields2 ;TestFields3;TestFields4

So I am using a sed command like that :

sed ':a;N;$!ba;s/[^;]\n/ /g'

The problem is that this command will replace also the character which is before \n so my outpu is like :

TestFields;TestFields ;TestFields3;TestFields4

I loose the '2' in the 'TestFields2' .. Someone have an idea on how to keep my character but replace the \n ?


Solution

  • capture the matched char and use in replacement

    $ sed -r ':a;N;$!ba;s/([^;])\n/\1 /g' file
    TestFields;TestFields2 ;TestFields3;TestFields4
    

    g suffix is probably not needed.