Howto: Linux command line utilities for removing blank lines from text files

https:/‮ual.www/‬tturi.com
Howto: Linux command line utilities for removing blank lines from text files

There are several ways to remove blank lines from a text file using Linux command line utilities. Here are three options:

  1. sed: You can use the sed command to delete blank lines from a file like this:
sed '/^$/d' input.txt > output.txt

This will delete all blank lines from input.txt and write the output to output.txt.

  1. grep: You can use the grep command to accomplish the same thing as follows:
grep -v '^$' input.txt > output.txt

This will search input.txt for lines that do not begin with the empty string (^$) and write the output to output.txt.

  1. awk: You can also use the awk command to remove blank lines from a file like this:
awk 'NF > 0' input.txt > output.txt

This will search input.txt for lines that have at least one field (NF > 0) and write the output to output.txt.

Note that in all of these examples, the input file (input.txt) is not modified. Instead, the output is written to a new file (output.txt). If you want to modify the input file in place, you can use the -i option with sed or awk, or use the tee command with grep like this:

grep -v '^$' input.txt | tee input.txt

This will search input.txt for lines that do not begin with the empty string and write the output to both input.txt and the terminal.

Created Time:2017-10-29 22:08:47  Author:lautturi