首页 > 解决方案 > 使用 sed 和 regexp 增加文件中的数字

问题描述

我想使用以下模式将文件中的所有数字增加 1000:

'... comment_count') VALUES ( 15132, ...
'... comment_count') VALUES ( 15133, ...
'... comment_count') VALUES ( 16134, ...
.
.

我希望更改后的输出是这样的:

'... comment_count') VALUES ( 16132, ...
'... comment_count') VALUES ( 16133, ...
'... comment_count') VALUES ( 17134, ...
.
.

我尝试了这样的事情但不起作用:

 sed -r 's/`comment_count`\) VALUES \( (\d+)/echo "\1\1$((\1+1000))\"/ge'  test.txt 

标签: stringunixsedfind

解决方案


sed不能在替换中进行数学或字符串操作。

您可以使用此perl解决方案:

perl -pe "s~(comment_count'\)\h+VALUES\h+\(\h+)(\d+)~\$1.(\$2+1000)~e" file

'... comment_count') VALUES ( 16132, ...
'... comment_count') VALUES ( 16133, ...
'... comment_count') VALUES ( 17134, ...

推荐阅读