5

In Print lines in file from the match line until end of file I learnt that you can use 0 in range expressions in awk to match until the end of the file:

awk '/matched/,0' file

However, today I started playing around this 0 and I found that this also works:

awk '/matched/,/!./' file

I guess 0 is working because in the range expression /regex1/,/regex2/ the lines are printed until the regex2 evaluates as True. And since 0 evaluates as False, this never happens and it ends up printing all the lines. Is this right?

However, with /!./ I would imagine this to work until a line without any character is found, like if we said awk '/matched/,!NF'. But it does not: instead, it always evaluates to False. What is the reasons for this?

Examples

$ cat a
1
matched
2

3
4
end

Both awk '/matched/,/!./' a and awk '/matched/,0' a return:

matched
2

3
4
end

Whereas awk '/matched/,!NF' a returns:

matched
2

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598

1 Answers1

4

You have exclamation at wrong place. Keep it outside the regex like this to negate the match:

awk '/matched/,!/./' a
matched
2


Your regex /!./ is matching a literal ! followed by any character.

If your file is this:

cat a
1
matched
2

3
!4
end

Then

awk '/matched/,/!./' a
matched
2

3
!4

And:

awk '/matched/,!/./' a
matched
2

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Oh! And what does `/!./` mean then? – fedorqui Feb 26 '15 at 12:41
  • That is matching `!` literally in regex followed by any character. – anubhava Feb 26 '15 at 12:42
  • 1
    Haha it's right! I just tried adding `hello!bye` somewhere after `match` and it prints until that point. Many thanks :) As per the range expression, I am right on saying "in the range expression /regex1/,/regex2/ the lines are printed until the regex2 evaluates as True."? – fedorqui Feb 26 '15 at 12:44
  • 1
    Yes that is absolutely right. It prints until `/regex2/` is found or EOF is reached. – anubhava Feb 26 '15 at 12:46
  • 1
    Thanks a lot for the complete answer. I am also glad to mark your answer as accepted for the first time after all this time being around knowledge :) – fedorqui Feb 26 '15 at 12:54
  • 1
    Thanks @fedorqui, I must add here that I have learnt many new things from your answers on SO. – anubhava Feb 26 '15 at 14:59