Sed替换URL中的域

时间:2014-06-25 20:32:46

标签: regex linux bash sed

我有这些字符串http://sub.domain.com/myuri/default.aspxhttps://sub.domain.com/myuri/default.aspxhttps://domain.com

是否可以使用sed仅替换域名部分?

例如,此网址:

http://sub.domain.com/myuri/default.aspx

会变成:

http://anotherdomain.com/myuri/default.aspx

请注意,协议可能因httpshttp而异。

我做了搜索,但找不到类似的东西。

5 个答案:

答案 0 :(得分:1)

如果我按照你的问题,那么是sed 's/sub\.domain\.com/anotherdomain\.com/1' -

echo "http://sub.domain.com/myuri/default.aspx" | \
  sed 's/sub\.domain\.com/anotherdomain\.com/1'

输出

http://anotherdomain.com/myuri/default.aspx

随着,

echo "https://sub.domain.com/myuri/default.aspx" | \
  sed 's/sub\.domain\.com/anotherdomain\.com/1'

输出

https://anotherdomain.com/myuri/default.aspx

答案 1 :(得分:1)

您需要sed无法提供的非贪婪模式,请改用perl:

perl -pe '/(http|https):\/\/(.*?)(\/|$)/ && s/$2/anotherdomain/g'

修改 awk也做得很好,实际上更简单:

awk -F/ 'gsub($3,"anotherdomain",$0)' <<< "$urls"

示例:

#!/bin/bash

urls=$(cat << 'EOF' 
https://sub.domain.com/myuri/default.aspx
http://sub.domain.com/myuri/default.aspx
http://blabla
EOF
)
perl -pe '/(http|https):\/\/(.*?)(\/|$)/ && s/$2/anotherdomain/g' <<< "$urls"

输出:

bash test.sh 
https://anotherdomain/myuri/default.aspx
http://anotherdomain/myuri/default.aspx
http://anotherdomain

答案 2 :(得分:0)

您可以像这样使用sed:

sed -r 's|(https?://)[^/]+([[^:blank:]]*)|\1anotherdomain.com\2|g' file
http://anotherdomain.comn.com/myuri/default.aspx
https://anotherdomain.comn.com/myuri/default.aspx
https://anotherdomain.comn.com

PS:在OSX上使用sed -E

答案 3 :(得分:0)

您可以使用sed:

SERVER=www.example.com
sed "s~https\?://\([^/]\+\)\(.*\)~http://$SERVER\2~" <<< "http://newsub.domain.com/myuri/default

答案 4 :(得分:0)

基于@ hek2mgl的解决方案:

SERVER=www.example.com
sed "s=\(https\?://\)[^/]\+=\1$SERVER=" \
    <<< 'https://anotherdomain.com/myuri/default.aspx'

将输出:

https://www.example.com/myuri/default.aspx

来自hek2mgl sed行的修改:

  • 稍微短一些(不需要在域名之后抓住部分将其粘贴到替换中)
  • 处理http://https://语法