There are times when we want to display only the actual lines in a file, leaving the blank lines. There are various methods in which we can print only the non-empty lines of a file.
1. The simplest of all is using the famous 'grep' command:
grep -v '^$' file
This is one of the most common methods used to get the non-empty lines of a file. The '^' is used to denote "lines beginning with", and '$' is used to denote "lines ending with". In this case, '^$' means a line beginning with and ending, which is nothing but a blank line. By using the -v options, we get the lines other than the blank lines.
2. Different ways of achieving the same thing in sed:
sed '/^$/D' fileThe above method removes('D') all the patterns(blank lines) matching and displays the rest.
sed -n '/^$/!p' fileThis form suppresses the default output(-n) and prints the non-empty(!p) lines.
3. Three different ways of getting non-empty lines using awk;
awk NF fileThis is my favourite of all. NF indicates the total number of fields, and hence this prints only non-blank lines, since in blank lines NF is 0 and evaluates to false.
awk 'length' fileThis one is almost same as the above, but uses the length function and prints only those lines whose length is > 0.
awk '$0 !~ /^$/' fileAn other option using awk as the previous methods. !~ indicates lines not containing.
4. Getting the non-empty lines using perl:
perl -lne 'print if length($_) ' fileThis is perl version of using the same in awk as before.
perl -lne 'print if $_ ne ""' file$_ indicates the current line. Prints only those lines which is not(ne) blank.
perl -ne 'print unless /^$/' file'print unless' indicates print lines which does not contain.