bash - 针对特定 URL 字符串操作的 bash 脚本
问题描述
我需要操作一个我不知道长度的字符串(URL)。
字符串类似于
https://x.xx.xxx.xxx/dontcare1/dontcare2/dontcareN/keyword/restofstring
我基本上需要一个返回这个的正则表达式:
https://x.xx.xxx.xxx/keyword/restofstring 其中 x 是当前 ip,每次都可能不同,我不知道 dontcares 的数量。
我实际上不知道该怎么做,在这个问题上花了 2 个小时,但没有找到解决方案。
谢谢!
解决方案
您可以sed
按如下方式使用:
sed -E 's=(https://[^/]*).*(/keyword/.*)=\1\2='
s
代表替代品,具有形式s=
搜索模式=
替换模式=
。搜索模式是一个正则表达式,我们在其中对要提取的部分进行了
分组。
替换模式使用和访问这些组。(...)
\1
\2
您可以将文件或标准输入提供给sed
它,它将逐行处理输入。
如果您有一个字符串变量并使用bash
,zsh
或类似的东西,您也可以使用<<<
.
bash 的示例用法:
input='https://x.xx.xxx.xxx/dontcare1/dontcare2/dontcareN/keyword/restofstring'
output="$(sed -E 's=(https://[^/]*).*(/keyword/.*)=\1\2=' <<< "$input")"
echo "$output" # prints https://x.xx.xxx.xxx/keyword/restofstring
推荐阅读
- java - Java 作业(初学者) - 我认为我的数学或声明有问题?
- github - 如何从 PC 中永久删除旧的 github 帐户
- jsf - 为什么单独的 RequestScoped bean 没有注入到 JSF commandButton 动作调用的 bean 中?
- android - 如何支持 sdk 28+ 的 64 位架构?
- python - + 不支持的操作数类型:'float' 和 'datetime.timedelta'", '发生在索引 5')
- c# - 尝试访问文件
- macos - 在安装 SMB 驱动器并在没有 root 的情况下读取它时遇到问题
- html - 如何在不拉伸的情况下将图像放入css-grid
- c# - 如何使用 C# 通过 Json 中的键名获取值列表
- google-apps-script - DriveApp 在环聊聊天机器人应用脚本中访问哪个帐户