6

I am trying to remove all blank lines from a text file using a Windows batch program.

I know the simplest way do achieving this is bash is via regular expressions and the sed command:

sed -i "/^$/d" test.txt

Question: Does Windows batch have an similar simple method for removing all lines from a text file? Otherwise, what is the simplest method to achieving this?

Note: I'm running this batch script to setup new Windows computers for customers to use, and so preferably no additional programs need to be installed (and then unistalled) to achieve this - ideally, I'll just be using the "standard" batch library.

andyandy
  • 1,384
  • 2
  • 15
  • 25

2 Answers2

8

For /f does not process empty lines:

for /f "usebackq tokens=* delims=" %%a in ("test.txt") do (echo(%%a)>>~.txt
move /y  ~.txt "test.txt"
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • I'm getting an error: "%%a was unexpected at this time." Any ideas? Also please can you explain what each word means in your answer (or point me to any doc that would help). Thanks! – andyandy Jan 21 '16 at 12:34
  • 2
    @andyandy, You are trying this in command prompt directly, true? if so, state `%a` instead of `%%a`... – aschipfl Jan 21 '16 at 12:45
  • @aschipfl Many thanks! Yes I was trying it in command prompt directly - works now. Can you explain what the **"usebackq tokens=* delims="** means please (I think I understand everything else)? – andyandy Jan 21 '16 at 12:54
  • 3
    @andyandy, type `for /?` in a command prompt window and read the help text; basically, `delims=` causes `for /F` to read each line as a whole, `tokens=*` is actually not needed here (but does no harm); `usebackq` allows the given file name `test.txt` to be placed within `""` (without `usebackq`, `test.txt` would be treated as literal string rather than a file path/name); `usebackq` and `""` are not needed here, but it is a good idea to use it though, because this way it works even with a file path/name containing spaces... – aschipfl Jan 21 '16 at 13:05
  • 1
    Althought it works fine for regular files, after processing a large file, the long lines are missing (> 62k characters). Be careful. – JCarlosR Oct 23 '19 at 18:59
6

You could also use FINDSTR:

findstr /v "^$" C:\text_with_blank_lines.txt > C:\text_without_blank_lines.txt

/V -- Print only lines that do NOT contain a match.
^ --- Line position: beginning of line
$ --- Line position: end of line

I usually pipe command output to it:

dir | findstr /v "^$"

You also might find these answers to a similar question helpful, since some 'blank lines' may include spaces or tabs.

https://stackoverflow.com/a/45021815/5651418
https://stackoverflow.com/a/16062125/5651418

noni
  • 139
  • 2
  • 8
  • much safer and faster than the `for` approach. Btw: also: `dir|findstr .`. The `.` is `findstr`'s wildcard for "any char" (so it finds each line that contains at least one char (besides the line ending) – Stephan Oct 17 '20 at 08:48