Reputation: 1197
I have a file with empty lines and section of animal names:
$ cat animals2
cat
dog
elephant
rhino
snake
hippo
eagle
camel
mouse
$
I would like to remove all the empty lines expect one, i.e. output should be:
$ cat animals2
cat
dog
elephant
rhino
snake
hippo
eagle
camel
mouse
$
..or:
$ cat animals2
cat
dog
elephant
rhino
snake
hippo
eagle
camel
mouse
$
My ideas was to process the file with sed
and:
Is there a way to compare pattern space with hold space in sed
?
Upvotes: 0
Views: 456
Reputation: 41460
Using -s
with cat
may be the simplest solution:
cat -s animals2
cat
dog
elephant
rhino
snake
hippo
eagle
camel
mouse
From man cat
:
-s, --squeeze-blank
suppress repeated empty output lines
This perl
will also do:
perl -00pe0 < animals2
Upvotes: 2
Reputation: 58528
This might work for you (GNU sed):
sed 'N;/^\n$/!P;D' file
Keep two lines in the pattern space and print the first one only when both are not empty.
Upvotes: 2
Reputation: 290235
As it is multiline processing, awk
can do it more efficiently:
awk '!NF {f=1; next} f {print ""; f=0} 1' file
It returns:
cat dog elephant rhino snake hippo eagle camel mouse
!NF {f=1; next}
if there are no fields --> the line is empty --> we set a flag on and we jump to the next line without further actions.1
perform the default awk action: print the current line.Upvotes: 3