View Single Post
  #5   (View Single Post)  
Old 18th June 2013
s0xxx's Avatar
s0xxx s0xxx is offline
Package Pilot
 
Join Date: May 2008
Posts: 192
Default

This might be the right occasion to exploit awk's "NF" built-in variable, which stands for the number of fields in the current input record separated by whitespace; whitespace in awk means any string of one or more spaces and/or tabs. So, NF is true if there are fields in the record:

Code:
$ cat -net test 
     1  FreeBSD$
     2  ^I ^I$
     3  DragonFlyBSD $
     4   $
     5  NetBSD$
     6  ^I  $
     7  OpenBSD$
     8    ^I  ^I$
     9  MirOS^I $

$ awk 'NF {print $0 "\n"}' test | cat -net
     1  FreeBSD$
     2  $
     3  DragonFlyBSD $
     4  $
     5  NetBSD$
     6  $
     7  OpenBSD$
     8  $
     9  MirOS^I $
    10  $
$
It says: "if there are fields in the record, print the record line and plus anotha newline; ignore all other lines".
To continue exploiting awk's other built-in variables, we might have written it as...
Code:
$ awk 'BEGIN{ORS="\n\n"} NF' test | cat -net -

       or

$ awk 'BEGIN{ORS=RS RS} NF' test | cat -net -
...or a bit more cryptic:
Code:
$ awk 'ORS=NF?RS RS:""' test | cat -net -
... which all do the same.

The only time it will not work is when you have multiple blank lines (containing either space, tabs or both) and you want to retain them, i.e. the format of the file. It that case, above awk command will only output a single newline.
Casual reader will notice an extra newline at the end, that is left as an exercise.

If one doesn't care about the format of the file and just want to kill all whitespace, then it's just a:
Code:
$ awk NF test | cat -net
     1  FreeBSD$
     2  DragonFlyBSD $
     3  NetBSD$
     4  OpenBSD$
     5  MirOS^I $
$
Simple heh?


P.S. I apologize for hijacking your thread @J65nko, I saw the others did and I had a bit of a inspirational moment...
__________________
The best way to learn UNIX is to play with it, and the harder you play, the more you learn.
If you play hard enough, you'll break something for sure, and having to fix a badly broken system is arguably the fastest way of all to learn. -Michael Lucas, AbsoluteBSD
Reply With Quote