我需要提取被标签包裹的URL。这是一个简单的正则表达式,但我不知道如何在shell脚本中实现。以下是示例:
line="<strong>http://www.example.com/index.php</strong>"
url=$(echo $line | sed -n '/strong>(http:\/\/.+)<\/strong/p')
我需要在
$url
变量中存储"http://www.example.com/index.php"。使用busybox。
这可能会起作用:
url=$(echo $line | sed -r 's/<strong>([^<]+)<\/strong>/\1/')
url=$(echo $line | sed -n 's!<strong>\(http://[^<]*\)</strong>!\1!p')
在正则表达式中,您不必使用反斜杠转义正斜杠。只有反斜杠需要在正则表达式中进行转义。当HTML源代码中存在多个强标签时,您还应该使用非贪婪匹配和?
运算符,以避免获取超出您所需的内容。
strong>(http://.+?)</strong
busybox
使用的是 ash
,因此假设使用 bash
特性的解决方案可能不起作用。仍然符合 POSIX 标准的稍微长一些的解决方案将会起作用:url=${line#<strong>} # $line minus the initial "<strong>"
url=${url%</strong>} # Remove the trailing "</strong>"
如果您正在使用bash
(或具有类似功能的其他shell),则可以将扩展模式匹配与参数替换相结合。(我不知道busybox支持哪些功能。)
# Turn on extended pattern support
shopt -s extglob
# ?(\/) matches an optional forward slash; like /? in a regex
# Expand $line, but remove all occurrances of <strong> or </strong>
# from the expansion
url=${line//<?(\/)strong>}