Regex sed试图更改日志文件中的主机名,但-(破折号,减号)导致问题
我是sed新手,需要更改大量大型日志文件中的数百个主机名 比如说Regex sed试图更改日志文件中的主机名,但-(破折号,减号)导致问题,regex,search,sed,replace,Regex,Search,Sed,Replace,我是sed新手,需要更改大量大型日志文件中的数百个主机名 比如说 URL:http://test-wls-1.compute-1234.cloud.internal .Response code: 503> 我需要把这个换成 URL:http[s]://hostname.compute-1234.cloud.internal: .Response code: 503> 我试过使用sed正则表达式 s'/http[s]\?:\/\/[^ ]./http[s]:\/\/hostna
URL:http://test-wls-1.compute-1234.cloud.internal .Response code: 503>
我需要把这个换成
URL:http[s]://hostname.compute-1234.cloud.internal: .Response code: 503>
我试过使用sed正则表达式
s'/http[s]\?:\/\/[^ ]./http[s]:\/\/hostname/'
但由于主机中的破折号被视为一个单词,因此它会返回
URL:http[s]://hostname-wls-1.compute-1234.cloud.internal .Response code: 503>
所以我需要一些帮助来了解我的错误
谢谢
事先您可以使用
sed 's~\(https\{0,1\}://\)[^.]\{1,\}~\1hostname~' # POSIX BRE
sed -E 's~(https?://)[^.]+~\1hostname~' # POSIX ERE
见:
s='URL:http://test-wls-1.compute-1234.cloud.internal .响应代码:503>'
sed的~\(https\{0,1\}://\)[^.]\{1,\}~\1hostname~'
详细信息
-第1组(在替换部分中用\(https\{0,1\}://\)
引用):\1
或http
然后https
字符串://
-1个或多个字符,而不是[^.]\{1,\}
-(RHS):组1值和\1hostname
子字符串hostname
/
),这样就不需要跳过很多斜杠。我将使用|
作为分隔符,此正则表达式将执行以下操作:
sed 's|http[s]\?://[^.]*|http[s]://hostname|'
http[s]\?://[^.]*
获取http://
或https://
与下一个点字符(在您的示例中,即http://test-wls-1
)并将其转换为http[s]://主机名,生成:
$ echo 'URL:http://test-wls-1.compute-1234.cloud.internal .Response code: 503>' |
sed 's|http[s]\?://[^.]*|http[s]://hostname|'
URL:http[s]://hostname.compute-1234.cloud.internal .Response code: 503>
您最初的尝试
http[s]\?:\/\/[^]。
匹配http://
或https://
,后跟任何非空格字符([^]
)和任何其他字符(
)。因此,输出将是
$ echo 'URL:http://test-wls-1.compute-1234.cloud.internal .Response code: 503>' |
sed 's/http[s]\?:\/\/[^ ]./http[s]:\/\/hostname/'
URL:http[s]://hostnamest-wls-1.compute-1234.cloud.internal .Response code: 503>
查看输出中缺少
test-…
中的te
。非常感谢Quasímodo的| http[s]\?://[^.]*| http[s]://hostname |工作顺利
$ echo 'URL:http://test-wls-1.compute-1234.cloud.internal .Response code: 503>' |
sed 's/http[s]\?:\/\/[^ ]./http[s]:\/\/hostname/'
URL:http[s]://hostnamest-wls-1.compute-1234.cloud.internal .Response code: 503>