我需要操作一个我不知道长度的字符串(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=
search pattern=
replacement pattern=
。
搜索模式是一个正则表达式,我们将(...)
分组为您要提取的部分。
替换模式使用\1
和\2
访问这些组。
您可以将文件或标准输入到sed
,它将逐行处理输入。
如果你有一个字符串变量并使用bash
,zsh
或类似的东西,你也可以使用<<<
将该变量直接输入stdin。
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
echo "https://x.xx.xxx.xxx/dontcare1/dontcare2/dontcareN/keyword/restofstring" | sed "s/dontcare[0-9]\+\///g"
sed用于操纵文本。 dontcare[0-9]\+\///g
是正则表达式dontcare[0-9]+/
的转义形式,它匹配单词“dontcare”后跟1位或更多位数,然后是/
字符。
sed的模式是这样的:s/find/replace/g
,其中g是一个允许你匹配模式的多个实例的命令。
你可以在行动here中看到正则表达式。
请注意,这假设字符串的其余部分没有dontcareN
s。如果是这样的话,Socowi的答案会更好。
您还可以使用read
和/
值来$IFS
来解析垃圾。
$: IFS=/ read proto trash url trash trash trash keyword rest <<< "https://x.xx.xxx.xxx/dontcare1/dontcare2/dontcareN/keyword/restofstring"
$: echo "$proto//$url/$keyword/$rest"
https://x.xx.xxx.xxx/keyword/restofstring
当dontcare...
值未知且可预测的字符串时,这更加通用。
这个是纯粹的bash,虽然我更喜欢Socowi's answer。
这是一个sed
变体,它从路径中挑选出宿主部分和最后两个成分。
url='http://example.com:1234/ick/poo/bar/quux/fnord'
newurl=$(echo "$url" | sed 's%\(https*://[^/?]*[^?/]\)[^ <>'"'"'"]*/\([^/ <>'"''"]*/^/ <>'"''"]*\)%\1\2%')
一般形式是sed 's%pattern%replacement%'
,其中模式匹配主机名部分的末尾(捕获到一组反斜杠括号中),然后跳过倒数第二个斜杠,然后捕获URL的其余部分,包括最后一个斜杠;并且替换只是召回两个被捕获的组而没有它们之间的跳过部分。