LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Remove lonely newline (https://www.linuxquestions.org/questions/linux-software-2/remove-lonely-newline-576184/)

samel_tvom 08-10-2007 12:02 PM

Remove lonely newline
 
Hi

I would like to remove all lonely newlines from a text file. By that I mean that this text:

Code:

a a a
b b b
c c c

d d d
e e e

f f f

would become
Code:

a a a b b b c c c
d d d e e e
f f f

Any suggestions? I tried an ugly hack with tr and sed:
Code:

cat "$1" |tr "\n" "@"| sed 's/@@/\n/g'|sed 's/@/ /g'
But that really messed up stuff and I'm not surprised.

colucix 08-10-2007 01:10 PM

Just an idea in awk:
Code:

/./ { string = string " " $0 }
! /./ { print string ;
        string = "" }
END { print string }

This concatenates non-empty lines (separated by one space) and print them when an empty line is encountered.

0.o 08-10-2007 01:10 PM

Didn't read the whole question.

http://www.student.northpark.edu/pem...d/sed1line.txt

This file still kicks ass.

samel_tvom 08-10-2007 02:37 PM

Colucix, yeah, I kinda suck at gawk. How would I implement it? If I have a textfile foo.txt that I would want that awk code to work on, how would I do?

colucix 08-10-2007 04:37 PM

To execute awk code you can put it in a file and execute with the -f option, as in
Code:

gawk -f program.awk foo.txt
or put awk statements directly on the command line, as in
Code:

gawk '{print $1}' foo.txt
You can also have a look at the Gawk: effective AWK Programming guide, a real must-read!

samel_tvom 08-11-2007 07:37 AM

Sweet! Thanks a lot!


All times are GMT -5. The time now is 09:05 PM.