gpt4 book ai didi

parsing - 在 shell 脚本中解析 URL

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:36 24 4
gpt4 key购买 nike

我有这样的网址:

sftp://user@host.net/some/random/path

我想从这个字符串中提取用户、主机和路径。任何部分都可以是随机长度。

最佳答案

[编辑 2019]这个答案并不意味着包罗万象,它适用于所有解决方案,它旨在为基于 python 的版本提供一个简单的替代方案,并且最终具有比原始版本更多的功能。


它以仅 bash 的方式回答了基本问题,然后由我自己多次修改以包含评论者的大量要求。我认为在这一点上增加更多的复杂性会使它变得难以维护。我知道并非所有事情都是直截了当的(例如,检查有效端口需要比较 hostporthost),但我不想增加更多的复杂性。


[原始答案]

假设您的 URL 作为第一个参数传递给脚本:

#!/bin/bash

# extract the protocol
proto="$(echo $1 | grep :// | sed -e's,^\(.*://\).*,\1,g')"
# remove the protocol
url="$(echo ${1/$proto/})"
# extract the user (if any)
user="$(echo $url | grep @ | cut -d@ -f1)"
# extract the host and port
hostport="$(echo ${url/$user@/} | cut -d/ -f1)"
# by request host without port
host="$(echo $hostport | sed -e 's,:.*,,g')"
# by request - try to extract the port
port="$(echo $hostport | sed -e 's,^.*:,:,g' -e 's,.*:\([0-9]*\).*,\1,g' -e 's,[^0-9],,g')"
# extract the path (if any)
path="$(echo $url | grep / | cut -d/ -f2-)"

echo "url: $url"
echo " proto: $proto"
echo " user: $user"
echo " host: $host"
echo " port: $port"
echo " path: $path"

我必须承认这不是最干净的解决方案,但它不依赖于其他脚本像 perl 或 python 这样的语言。(提供使用其中之一的解决方案会产生更清晰的结果;))

使用您的示例,结果是:

url: user@host.net/some/random/path
proto: sftp://
user: user
host: host.net
port:
path: some/random/path

这也适用于没有协议(protocol)/用户名或路径的 URL。在这种情况下,相应的变量将包含一个空字符串。

[编辑]
如果你的 bash 版本不能处理替换 (${1/$proto/}) 试试这个:

#!/bin/bash

# extract the protocol
proto="$(echo $1 | grep :// | sed -e's,^\(.*://\).*,\1,g')"

# remove the protocol -- updated
url=$(echo $1 | sed -e s,$proto,,g)

# extract the user (if any)
user="$(echo $url | grep @ | cut -d@ -f1)"

# extract the host and port -- updated
hostport=$(echo $url | sed -e s,$user@,,g | cut -d/ -f1)

# by request host without port
host="$(echo $hostport | sed -e 's,:.*,,g')"
# by request - try to extract the port
port="$(echo $hostport | sed -e 's,^.*:,:,g' -e 's,.*:\([0-9]*\).*,\1,g' -e 's,[^0-9],,g')"

# extract the path (if any)
path="$(echo $url | grep / | cut -d/ -f2-)"

关于parsing - 在 shell 脚本中解析 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34003858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com