Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty lines in text using Visual Studio

People also ask

How do I remove blank lines in a text file?

Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box.

How do I get rid of empty lines?

There is also a very handy keyboard shortcut to delete rows (columns or cells). Press Ctrl + – on the keyboard. That's it! Our blank rows are gone now.


Since Visual Studio 2012 changed its regex syntax, the original answers by Ala translate into the following in VS 2012:

Remove single blank lines

Old:

^:b*$\n

New:

^(?([^\r\n])\s)*\r?$\r?\n

Visual Studio 2013 (thanks to BozoJoe and Joe Johnston):

^\s*$\n

Remove double blank lines

Old:

^:b*\n:b*\n

New:

^(?([^\r\n])\s)*\r?\n(?([^\r\n])\s)*\r?\n

Rolls right off your tongue.

Here is the conversion sheet from MSDN.


It's very useful especially if you want to arrange or compare codes, thanks for the people who answer this question, I've got the answer from here and would like to share it with Stackoverflow:

Visual Studio has ability to delete empty lines in replace operation using regular expressions.

  • Click Ctrl-H (quick replace)

  • Tick "Use Regular Expressions"

  • In Find specify ^$\n

  • In Replace box delete everything.

  • Click "Replace All"

All empty lines will be deleted.

Regular expression for empty line consist of

Beginning of line ^

End of line $

Line break \n

Note that normally in Windows an end of line indicated by 2 characters crlf - Carriage Return (CR, ASCII 13, \r) Line Feed (LF, ASCII 10, \n).

A regex to remove blank lines that are/aren't really blank (i.e. they do/don't have spaces): ^:b*$\n

To remove double lines: ^:b*\n:b*\n replace with: \n

* for Visual Studio 2013 and above:*

^\s*$\n

and for double lines:

^(?([^\r\n])\s)*\r?\n(?([^\r\n])\s)*\r?\n

See the regular expression syntax updates for VS2012 and above in @lennart's answer below


Using Visual Studio 2017 and above

in Current Document

use shortcut

  • Open Tools > Options or press Alt + T + O
  • Under Environment tab > Keyboard
  • Search for "DeleteBlank" and select Edit.DeleteBlankLines
  • Add a new shortcut for example Ctrl+D,Ctrl+E
  • Assign > OK

select all text and hit the shortcut

enter image description here


In Visual Studio 2013 (Version 12.0.20623.01) i removed empty lines with this regular expression ^\r\n In the screen you can see the matched lines indicated by the brown squares.

Visual Studio 2013 replace empty lines


Tested in VS 2012 to allow for pure line feeds.

^\s*$\n 

hth