Search code examples
awkblank-line

How can I exclude blank lines with awk?


Question

How can I exclude lines starting with a space character, and that have nothing else on the line? With awk, I want to print the line Need to print, but it's also printing the blank line. How can I exclude it?

Script: test.awk

$0 !~/^start|^#/ {
print "Result : %s",$0
}

Data

# test

start
Need to print

Result

Result : %s 
Result : %s Need to print

Solution

  • Use the NF Variable

    You aren't really asking about lines that start with a space, you're asking about how to discard blank lines. Pragmatically speaking, blank lines have no fields, so you can use the built-in NF variable to discard lines which don't have at least one field. For example:

    $ awk 'NF > 0 && !/^(start|#)/ {print "Result: " $0}' /tmp/corpus 
    Result: Need to print