Question more or less says it all. I'm aware that /^$/d
will remove all blank lines, but I can't see how to say 'replace two or more blank lines with a single blank line'
Any ideas?
Question more or less says it all. I'm aware that /^$/d
will remove all blank lines, but I can't see how to say 'replace two or more blank lines with a single blank line'
Any ideas?
If you aren't firing vim or sed for some other use, cat actually has an easy builtin way to collapse multiple blank lines, just use cat -s
.
If you were already in vim and wanted to stay there, you could do this with the internal search and replace by issuing: :%s!\n\n\n\+!^M^M!g
(The ^M is the visual representation of a newline, you can enter it by hitting Ctrl+vEnter), or save yourself the typing by just shelling out to cat: :%!cat -s
.
Use \n
to indicate a newline in the search pattern. Use Ctrl+M in the replacement text, or a backreference. See :help pattern
and :help sub-replace-special
(linked from :help :s
).
%s/\(\n\n\)\n\+/\1/
\n
doesn't work in the replacement text.
– Gilles 'SO- stop being evil'
Nov 23 '17 at 19:24
nnoremap <Leader>x :%s/\(\n\n\)\n\+/\1/gc<CR>
to my .vimrc
; thanks coming up with the regex. Yours is much cleaner than the accepted answer.
– Luke Davis
Feb 09 '18 at 11:24
\v
as well: %s/\v(\n\n)\n+/\1/
– cmaceachern
Oct 28 '22 at 16:01
If in Vim, just do this:
:%!cat -s
The -s
flag for cat
squeezes multiple blank lines into one.
man
page.
– jasonwryan
Nov 21 '12 at 05:22
!
will execute a shell command. cat
is a Unix shell command, the equivalent command in Windows is type
, but it does not condenses empty lines. Look for the other answers that use the substitute command (s
)
– Thiago Chaves
Jun 24 '22 at 17:28
Using Perl:
perl -00 -pe ''
-00
command line option turns paragraph slurp mode on, meaning Perl reads text paragraph by paragraph rather than line by line.
With sed (GNU sed) 4.2.2:
sed -r '
/^\s*$/ {
# blank line
:NEXT
N # append next line to pattern space - if none, autoprint PS and exit
s/^\s*$\n^\s*$//g;t NEXT # if 2 blank lines, clear PS and loop to NEXT
}
# else, autoprint PS and next/exit
' < $MYFILE
I know this is silly code, but I wanted to solve this issue in less than 10 min, and it worked
for file in /directory/*
do
originalname=$file
us='_'
tempname=$file$us
echo $originalname
mv $originalname $tempname
uniq $tempname $originalname
rm $tempname
done
-s
option of cat - just a historic note, it is not in POSIX, but seems to be available in BSD and GNU cat. – maxschlepzig May 07 '11 at 20:40:%!cat -s
. Learn something GNnew everyday! – Andrew Bolster May 07 '11 at 20:43%s!\n\n\n\+!\r\r!g
– Niko Bellic May 28 '17 at 22:32fmt
command to do hard word wrapping on text andunexpand
to convert spaces to tabs. – silicontrip Feb 16 '21 at 06:08