You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sed替换操作中使用当前行号进行内容替换?

Sed 能否识别行号并将其用于替换操作?

当然没问题!Sed 完全支持识别当前行号,还能把它直接嵌入到替换操作里,刚好能实现你想要的——把所有 foo 替换成 (x) bar(其中 x 是当前行号)的需求。

基础实现方法

Sed 里有个特殊的转义序列 \=,在替换的目标字符串中使用它,就会被替换成当前行的行号。举个实际的例子:

假设你有一个文本文件 test.txt,内容如下:

foo
hello foo
foo world
another line with foo and foo

执行下面的 Sed 命令:

sed 's/foo/(\=) bar/g' test.txt

输出结果会是:

(1) bar
hello (2) bar
(3) bar world
another line with (4) bar and (4) bar

这里的 g 标记表示全局替换——也就是一行里所有的 foo 都会被替换成带当前行号的内容。如果只想替换每行第一个出现的 foo,去掉 g 标记即可:

sed 's/foo/(\=) bar/' test.txt

进阶:自定义行号格式

如果需要给行号添加格式(比如补前导零变成两位数字),可以结合 printf 命令和 Sed 的 e 选项(让 Sed 执行替换后的命令并把输出作为结果):

sed 's/foo/printf "(%.2d) bar" \=/e' test.txt

这个命令会把行号格式化为两位数字,输出结果类似:

(01) bar
hello (02) bar
(03) bar world
another line with (04) bar and (04) bar

总结

核心就是利用 Sed 的 \= 转义序列来插入当前行号,简单场景直接用基础替换命令就能搞定,复杂格式需求可以结合外部命令扩展实现。

内容的提问来源于stack exchange,提问作者justin cress

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:32:58