我想在输入文件中为所有行编号,除此之外,与我的正则表达式相匹配.例如:
输入文件:
some text 12345
some another text qwerty
my special line
blah foo bar
Run Code Online (Sandbox Code Playgroud)
Regexp:^我的
输出:
1 some text 12345
2 some another text qwerty
my special line
3 blah foo bar
Run Code Online (Sandbox Code Playgroud)
awk可以很容易地做到这一点.Awk脚本:
!/^my/ {
cnt++;
printf "%d ", cnt
}
{
print
}
Run Code Online (Sandbox Code Playgroud)
这意味着:对于与表达式不匹配的所有行,递增变量cnt(从零开始)并打印该数字后跟空格.然后打印整行.
演示:
$ awk '!/^my/{cnt++; printf "%d ", cnt} {print}' input
1 some text 12345
2 some another text qwerty
my special line
3 blah foo bar
Run Code Online (Sandbox Code Playgroud)
Thor的精简版:
$ awk '!/^my/{$0=++cnt" "$0} 1' input
Run Code Online (Sandbox Code Playgroud)
这可以通过$0在行与表达式不匹配时修改整行()(在预先递增的计数器之前).
在1第一后pattern{action}对本身是pattern{action}其中省略了作用部对.1始终为true,因此始终执行操作,并且在未指定时执行默认操作{print}.并且print没有参数列表相当于print $0,即打印整行.
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |