How to remove empty lines from file in Unix
Introduction
Removing empty lines in a text file from the Unix shell is quite easy. There are a couple of ways to do that. Let us explore a few…
Remove empty lines using sed command
The stream editor (sed) can be used to filter and transform text. Removing empty lines using sed can be done using a regular expression and the (d) option.
1 2 3 4 |
# ^ begins # $ ends # d delete sed '/^$/d' empty.txt > out.txt |
Remove empty lines using grep command
Grep command can be used to search for a text pattern. We can utilize that and search for non empty lines and direct the output to a file or the console.
1 2 3 4 5 6 7 8 |
# [^[:blank:]] means search for non blank lines cat empty.txt | grep '[^[:blank:]]' > out.txt # The grep command can also be used as cat empty.txt | grep . > out.txt # Or this grep -v -e '^$' empty.txt > out.txt |
Remove empty lines using awk command
NF in awk evaluates to the number of fields in the line. If the line is not empty, NF is greater than zero which triggers the default awk action (i.e printing the whole line)
1 2 |
# Print the whole line if non empty awk 'NF' empty.txt > out.txt |
References
Thanks for visiting
More from my site
About Author
Mohammed Abualrob
Software Engineer @ Cisco