I’d like to number all lines in my input file, except for this, that match my regexp. Ex:
Input file:
some text 12345
some another text qwerty
my special line
blah foo bar
Regexp: ^my
Output:
1 some text 12345
2 some another text qwerty
my special line
3 blah foo bar
awkcould do that pretty easily. Awk script:Which means: for all lines that don’t match the expression, increment the variable
cnt(which starts out at zero) and print that number followed by a space. Then just print the whole line.Demo:
A condensed version thanks to Thor:
This works by modifying the whole line (
$0) when the line doesn’t match the expression (prepending the pre-incremented counter).The
1after the firstpattern{action}pair is itself apattern{action}pair with the action part omitted.1is always true, so the action is always executed, and the default action when none is specified is{print}. Andprintwith no argument list is equivalent toprint $0, i.e. print the whole line.