首页 > 解决方案 > 针对特定 URL 字符串操作的 bash 脚本

问题描述

我需要操作一个我不知道长度的字符串(URL)。

字符串类似于

https://x.xx.xxx.xxx/dontcare1/dontcare2/dontcareN/keyword/restofstring

我基本上需要一个返回这个的正则表达式:

https://x.xx.xxx.xxx/keyword/restofstring 其中 x 是当前 ip,每次都可能不同,我不知道 dontcares 的数量。

我实际上不知道该怎么做,在这个问题上花了 2 个小时,但没有找到解决方案。

谢谢!

标签: bash

解决方案


您可以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

推荐阅读