Tuesday, June 1, 2010

Different ways to print non-empty lines in a file



 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' file
      The above method removes('D') all the patterns(blank lines) matching and displays the rest.
sed -n '/^$/!p' file
     This 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 file
     This 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' file
      This one is almost same as the above, but uses the length function and prints only those lines whose length is > 0.
awk '$0 !~ /^$/' file
      An 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($_) ' file
      This 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.

1 comment: