0

One line starting with \hello is skipped using

awk '/\\hello/{next}'

How to edit the command above to skip lines between \hello and \hello2?

input

text
\hello
text
hi
\hello2
text2

desired output:

text
text2
Archie
  • 93
  • 2
  • 9
  • What if there's never a `\hello2` - should the text starting with `\hello` be printed or not. And there are no patterns - always state if you're talking about strings or regexps. – Ed Morton Nov 05 '19 at 21:48

1 Answers1

3

In its not recommended way, you can do the following:

$ awk '/^\\hello$/,/^\\hello2$/{next}1' file

The better, more adaptable way is:

$ awk '/^\\hello$/{f=1}(f==0){print};/^\\hello2$/{f=0}' file

which is reducible too:

$ awk '/^\\hello$/{f=1}!f;/^\\hello2$/{f=0}' file

or see Ed Morton's comment (see below)

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • Why would using the *regex range pattern* expression not be recommended? It is provided for in `man 1 awk`? (see `pattern1,pattern2` under the `"Patterns"` heading) and is supported by both `gawk` and POSIX `awk`. – David C. Rankin Nov 05 '19 at 20:58
  • 1
    `[\\]` is just "\\" – KamilCuk Nov 05 '19 at 21:02
  • 1
    @DavidRankin-ReinstateMonica see https://stackoverflow.com/questions/23934486/is-a-start-end-range-expression-ever-useful-in-awk – Ed Morton Nov 05 '19 at 21:43
  • FWIW: `awk '$0=="\\hello"{f=1} !f; $0=="\\hello2"{f=0}' file` – Ed Morton Nov 05 '19 at 21:52
  • 1
    @EdMorton - Thank You. That does add clarity to the pros and cons of the use of a range pattern. I have to admit, I have only considered range patterns for use with `sed` prior to this question, and went to the man pages to determine whether it was `gawk` limited or was POSIX as well. [man 1 gawk](http://man7.org/linux/man-pages/man1/gawk.1.html) and [man 1.p awk](http://man7.org/linux/man-pages/man1/awk.1p.html) I agree with the rational you posted as well as here, that the range pattern is better avoided -- learning has occurred -- it's been a good day. – David C. Rankin Nov 06 '19 at 00:18