views:

143

answers:

6

I have a file where I want to convert "\n" to " " and "\n\n" to "\n". For example:

I
had
a
toy
.

It
was
good
.

Becomes:

I had a toy .
It was good .

Does anyone have a Unix one-liner for this operation?

+3  A: 
fmt | sed '/^$/d'

The fmt command will wrap lines at 75 characters, so use fmt -w [WIDTH] to set longer lines.

bmb
Do you even need the sed command here? I thought fmt would handle this on its own.
acrosman
acrosman, I tried w/o using sed. I couldn't find an option to fmt that would remove the blank line.
bmb
A: 

If you had installed Ruby ,this is the one-liner that do the trick.

irb(main):014:0> puts f.gsub(/[a-zA-Z.](\n)/) {|s| s.chomp +" "}
I had a toy . 
It was good .
pierr
A: 

I think bmb's comment to his/her own answer hinted at the difficulty you may have had if you 'googled' for suggestions.

Google 'remove blank lines'.

Maybe fmt won't do it by itself, but there are many methods.

I liked the grep approach

grep -v "^$" filename > newfilename

although it's a little messy to have to rename the file.

EDIT: one of the hits found by 'remove blank lines Perl' gave

perl -pi -e "s/^\n//" file.txt
pavium
grep doesn't have the ability to "modify" content.
ghostdog74
but it's not modifying content - it's just filtering out blank lines and sending them to a different file.
pavium
oops, I mean grep is sending *everything but* the blank lines to a different file. Grep is a **filter**, and pretty useful at that.
pavium
You could avoid renaming by using sponge from the moreutils package. grep -v "^$" filename | sponge filename
Kalmi
I would probably avoid renaming the file, and avoid a pipeline, by invoking perl in 'edit in place' mode.
pavium
Neither of these solutions converts "\n" to " "
bmb
True, that requirement has been overlooked. I must look at the documentation for fmt. I don't have it in Cygwin.
pavium
Hmm ... **!}fmt** has promise as a means of formatting paragraphs in vim.
pavium
A: 

The first thing I can think of is this:

tr '\n' '#' | sed 's/##/\n/g' | sed 's/#//g'

Where # is some character not used in the file, that's the downside of it. You'll have to use some unique character ;)

WoLpH
+3  A: 

if you have gawk

# awk 'BEGIN{RS=""}{$1=$1}1'  file
I had a toy .
It was good .
ghostdog74
+1 nice! This doesn't have the line length limit that my answer has.
bmb
+1  A: 

Yet another Awk solution:

$ cat data.txt 
I
had
a
toy
.

It
was
good
.

$ awk '{printf "%s ", $0} /^$/{print ""}' data.txt 
I had a toy .  
It was good .
Hai Vu