如何在 unix 中将后缀附加到所有字符串匹配的正则表达式

How to append suffix to all string matched regular expression in unix

我需要用文件中带有后缀的相同字符串替换所有出现的特定格式的字符串(在我的例子中是冒号后跟一些数字),如下所示:

:123456 -> :123456_suffix

有没有办法用 sed 或其他 unix 命令行工具做到这一点?

Sed 应该这样做:

sed -i~ -e 's/:\([0-9]\{1,\}\)/:_suffix/g' file
                ^  ^  ^      ^   ^        ^
                |  |  |      |   |        |
    start capture  |  |    end   |  globally, i.e. not just the first
    group          |  | capture  |              occurrence on a line
           any digit  |          the first capture
                 one or          group contents
                 more times

如果不支持-i,只需创建一个新文件并替换旧文件:

sed ... > newfile
mv oldfile oldfile~ # a backup
mv newfile oldfile

使用 sed,

sed 's/\(:[0-9]\+\)/_suffix/g' file

如果您想进行就地编辑,请添加 -i 修饰符。