regex - 我在 Linux 中使用带有正则表达式的 sed 但没有得到预期的答案

标签 regex linux bash sed

我有一个文件,里面的内容是这样的

1234 Name Surname Address

我应该有这样的输出文件

(123) Name Surname Address

我正在使用 Linux sed 命令

sed -e 's/^\([0-9]\{3\}\)\./&/g' file_name

但是我的命令根本没有改变输入文件。

请帮忙,

最佳答案

你不需要两个捕获组,一个就够了,也不需要捕获数字后面的剩余字符,

$ sed 's/\([0-9]\{3\}\)[0-9]/(\1)/g' file
(123) Name Surname Adress

通过 GNU sed,

$ sed -r 's/([0-9]{3})[0-9]/(\1)/g' file
(123) Name Surname Adress

解释:

([0-9]{3})  # Captures first three numbers.
[0-9]       # Matches the last number.
(\1)        # In the replacement part, it replaces the four numbers by `(captured group)`

关于regex - 我在 Linux 中使用带有正则表达式的 sed 但没有得到预期的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339369/

相关文章:

regex - 如何从字符串中提取信息

linux - 使用 Shell 脚本内容保存文件

bash - stdoutput 和 stderror 的重定向不捕获所有输出

java - 正则表达式:索引附近未封闭的字符类

Java正则表达式提示错误字符

linux - 我可以在MacOS的_start处通过代码执行 `ret`指令吗? Linux的?

java - Runtime.exec() 无法运行 "su - postgres -c ' pg_dump .. .'"

r - 无法从 R 中的文本中提取名称

Python 正则表达式 逗号 Delim

java - SSL 身份验证问题