26

The /./ is removing blank lines for the first condition { print "a"$0 } only, how would I ensure the script removes blank lines for every condition ?

awk -F, '/./ { print "a"$0 } NR!=1 { print "b"$0 } { print "c"$0 } END { print "d"$0 }' MyFile
general exception
  • 4,202
  • 9
  • 54
  • 82
  • 2
    `awk '/./' MyFile` ? `awk NF` http://www.unix.com/shell-programming-scripting/84923-remove-all-blank-lines-shell-awk.html http://www.tek-tips.com/viewthread.cfm?qid=1282604 – ant Apr 27 '12 at 08:55
  • I would say it's time to change the accepted answer, except I think @oliv's answer is even better than the one with 25 upvotes so I want to give it time to rise. – Noumenon Jan 21 '18 at 22:48

4 Answers4

73

A shorter form of the already proposed answer could be the following:

awk NF file

Any awk script follows the syntax condition {statement}. If the statement block is not present, awk will print the whole record (line) in case the condition is not zero.

NF variable in awk holds the number of fields in the line. So when the line is non empty, NF holds a positive value which trigger the default awk action (print the whole line). In case of empty line, NF is zero and the condition is not met, so awk does nothing.

Note that you don't even need quote because this 2 letters awk script doesn't contain any space or character that could be interpreted by the shell.


or

awk '!/^$/' file

^$ is the regex for an empty line. The 2 / is needed to let awk understand the string is a regex. ! is the standard negation.

oliv
  • 12,690
  • 25
  • 45
40

Awk command to remove blank lines from a file:

awk 'NF > 0' filename
mtvec
  • 17,846
  • 5
  • 52
  • 83
Aaykay
  • 401
  • 3
  • 2
17

if you want to ignore all blank lines, put this at the beginning of the script

/^$/ {next}
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

Put following conditions inside the first one, and check them with if statements, like this:

awk -F, '
    /./ { 
        print "a"$0; 
        if (NR!=1) { print "b"$0 } 
        print "c"$0 
    } 
    END { print "d"$0 }
' MyFile
Birei
  • 35,723
  • 2
  • 77
  • 82