Sigularity
Sigularity

Reputation: 967

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

Upvotes: 1

Views: 2979

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

You can use:

awk '/^[^[:space:]]/{print "Result : " $0}'

The use of [^[:space:]] ensures that there is at least a single non space character in every line which get's printed.

Upvotes: 3

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

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

Upvotes: 4

Related Questions