简体   繁体   English

通过使用sed wit regexp进行替换

[英]Replacing by using sed wit regexp

Need to replace string in a file with regular expression. 需要用正则表达式替换文件中的字符串。 My regexp is api.(dev[0-9]+\\.)?side.com and I am using it with call: 我的正则表达式是api.(dev[0-9]+\\.)?side.com ,我正在将其与call一起使用:

sed "s/api.(dev[0-9]+\.)?side.com/$SERVER_HOST_VALUE/g"

But it didn't found any strings like "api.side.com" or "api.dev02.side.com". 但找不到任何类似“ api.side.com”或“ api.dev02.side.com”的字符串。 Regular expression worked for me and not worked only with "sed" command. 正则表达式对我有用,而不仅仅是使用“ sed”命令。

So how to use current regexp properly with sed ? 那么,如何在sed正确使用当前的正则表达式呢?

Based on @fedorqui's and @hwnd's recommendation, use the -r option : 根据@fedorqui和@hwnd的建议,使用-r选项

sed -re "s/api.(dev[0-9]+\.)?side.com/$SERVER_HOST_VALUE/g"

Note: If you use single quotes instead of double quotes, the variable $SERVER_HOST_VALUE won't be expanded. 注意:如果使用单引号而不是双引号,则不会扩展变量$SERVER_HOST_VALUE

Test 测试

SERVER_HOST_VALUE="AWESOME"
tests=( "api.side.com" "api.dev05.side.com" )
for t in "${tests[@]}"; do 
    echo "$t" | sed -re "s/api.(dev[0-9]+\.)?side.com/$SERVER_HOST_VALUE/g"
done

Output 输出量

Note how the matches are replaced by $SERVER_HOST_VALUE : 注意如何用$SERVER_HOST_VALUE替换匹配$SERVER_HOST_VALUE

AWESOME
AWESOME

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM