Regex 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

我是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]:\/\/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~'
详细信息

  • \(https\{0,1\}://\)
    -第1组(在替换部分中用
    \1
    引用):
    http
    https
    然后
    ://
    字符串
  • [^.]\{1,\}
    -1个或多个字符,而不是
  • \1hostname
    -(RHS):组1值和
    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>