Sed使用行号代替

时间:2018-04-20 23:36:47

标签: sed

sed是否知道它在哪一行,是否可以将其替换?即找到所有出现的foo并替换为(x)bar,其中x是行号

1 个答案:

答案 0 :(得分:3)

Sed有一个命令=,它只将行号打印到stdout。

您可以像这样使用它:

sed '=' YOURFILE | sed 'N; s/^\([0-9]\+\)\(.*\)\(NEEDLE\)/\1\2(\1) REPLACEMENT/; s/^[0-9]\+\n//'

示例输入文件roses

Roses are red,
Violets are blue,
sugar is sweet,
And so are you.

示例命令:

sed '=' roses | sed 'N; s/^\([0-9]\+\)\(.*\)\(blue\)/\1\2(\1) violet/; s/^[0-9]\+\n//'

示例输出:

Roses are red,
Violets are (2) violet,
sugar is sweet,
And so are you.

当然,这对AWK来说更简单:

awk '{ gsub(/NEEDLE/,"("NR") REPLACEMENT") } 1' YOURFILE

等效示例:

awk '{ gsub(/blue/,"("NR") violet") } 1' roses