首页 > 解决方案 > 使用 sed 命令交换字符串中的第二个和第六个字符

问题描述

我写了一个 sed 命令来交换下面数字中的第二个和第六个字符。

我收到以下错误:

sed: file minor1.sed line 4: invalid reference \9 on `s' command's RHS

我的 sed 命令(script.sed):

s/\(.\){10}/\1\6\3\4\5\2\7\8\9\10/g

我正在使用 sed -r -f script.sed Input.txt 运行命令。

输入.txt -

8668797647
8884747424
3716706006
8662665588

谁能帮我弄清楚为什么我会收到这个错误?

标签: regexsedswap

解决方案


试试这个:

sed -E 's/^\(.\)\(.\)\(...\)\(.\)/\1\4\3\2/'

这将捕获编号如下的组中的数字:

Input:  abcdefghij
Group:  123334  (the capture group of the digit above)
Result: afcdebghij

只有前 6 位数字被匹配/替换。


推荐阅读