Awk

From Leo's Notes
Revision as of 22:21, 22 May 2013 by Leo (talk | contribs) (Created page with " == Counting Lines Until Match == To print the number of lines before a match is found: awk 'BEGIN { n = 0 } /PATTERN/ { print n; next } { n++ }' Eg: Suppose I have a file ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
This page was last edited on 22 May 2013, at 22:21.

Counting Lines Until Match

To print the number of lines before a match is found:

awk 'BEGIN { n = 0 } /PATTERN/ { print n; next } { n++ }'

Eg: Suppose I have a file with the contents:

leo
spoon
cake
fork

To find the number of lines up until 'cake', do:

cat list.txt | awk 'BEGIN { n = 0 } /cake/ { print n; next } { n++ }'