颠倒一行中前 3 位数字的顺序

Sod*_*oda 1 bash sed gawk

我正在尝试为大学做作业,但我目前被困住了。目标是读取一些电话号码并颠倒前 3 位数字的顺序并将它们放在括号中。我可以让它读取电话号码,但不能反转数字。

例如:输入

214 4234-5555
Run Code Online (Sandbox Code Playgroud)

例如:输出

412 4234-5555
Run Code Online (Sandbox Code Playgroud)

这是我迄今为止所拥有的

sed -r "s/([0-9]), ([0-9]), ([0-9])/\3\2\1/g" phone.txt
Run Code Online (Sandbox Code Playgroud)

Sun*_*eep 5

修改OP的尝试

$ cat ip.txt
214 4234-5555
foo 123 4533-3242

$ sed -r 's/([0-9])([0-9])([0-9])/\3\2\1/' ip.txt
412 4234-5555
foo 321 4533-3242

$ # adding parenthesis as well
$ sed -r 's/([0-9])([0-9])([0-9])/(\3\2\1)/' ip.txt
(412) 4234-5555
foo (321) 4533-3242

$ # if ERE is not supported
$ sed 's/\([0-9]\)\([0-9]\)\([0-9]\)/(\3\2\1)/' ip.txt
(412) 4234-5555
foo (321) 4533-3242
Run Code Online (Sandbox Code Playgroud)
  • 请注意,某些sed实现将需要-E而不是-r
  • 除非需要插值,否则请使用单引号,另请参阅https://mywiki.wooledge.org/Quotes
  • ([0-9]), ([0-9]), ([0-9]) 表示匹配由逗号和空格分隔的 3 位数字
  • g 如果应该更改一行中的所有匹配项,则需要修饰符


对于通用解决方案,即定义要反转的位数作为数字参数

$ perl -pe 's/\d{3}/reverse $&/e' ip.txt
412 4234-5555
foo 321 4533-3242
$ perl -pe 's/\d{3}/sprintf "(%s)", scalar reverse $&/e' ip.txt
(412) 4234-5555
foo (321) 4533-3242
Run Code Online (Sandbox Code Playgroud)