简体   繁体   中英

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 ?

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.

This might work for you (GNU sed):

sed ':a;N;/;\n/!s/\n/ /;ta;P;D' file

An alternative to slurping the whole file into memory and reads as the question was read ie if the character preceeding the newline is a ; do nothing otherwise replace the newline by a space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM