1

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
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
Sigularity
  • 917
  • 2
  • 12
  • 28
  • The 2 answers you have will behave differently when a line contains only blank chars - which solution you need depends on whether such a line should be considered a "blank line" or not for your purposes. – Ed Morton Feb 18 '16 at 16:05

2 Answers2

4

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
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 2
    `NF > 0` can be replaced with `NF`. – karakfa Feb 18 '16 at 14:51
  • @karakfa Possibly, as it works with BSD and GNU awk. However, I'm not sure how portable that is across all awks. Even if it's 100% portable, brevity never trumps clarity of intent. I always prefer my code to be clear about comparisons, rather than using implicit comparisons that are difficult for future readers to reason about. YMMV. Nevertheless, thanks for the tip! – Todd A. Jacobs Feb 19 '16 at 08:09
  • I agree in principle, but `awk 'NF'` is idiomatic awk to print non empty lines. – karakfa Feb 19 '16 at 13:44
3

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.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • The leading `^` in `/^[^[:space:]]/` means it would skip any lines that have indented non-space text. It's not 100% clear from the question since the sample input didn't include that case but that's usually not what people mean when they say they want to `exclude lines starting with a space character, and that have nothing else on the line`. – Ed Morton Feb 18 '16 at 16:08