找到字符串标签并使用SED将其替换为超链接



新的SED,并试图使用它来找到一个自定义字符串标记和替换为html超链接,但不能得到下面的SED格式正确工作。谢谢你的帮助。

简介:在字符串中找到DEV-XXXX并替换w/html超链接,DEV- string标签将始终保持不变,但XXXX数字引用可以根据不同的字符串而变化。

"This is a test of DEV-1212"

"This is a test of DEV-1213 more text"

预期结果:

"This is a test of <a href="https://devtest.net/DEV-1212">DEV-1212</a>"

"This is a test of <a href="https://devtest.net/DEV-1215">DEV-1213</a> more text"

这是我一直在使用的SED语法,但还不能使它正确工作。

$ echo "This is a test DEV-1212" | sed -r 's/DEV-^[^0-9]*([0-9]+).*/<a href="https://devtest.net/&">&</a>/'

**产生以下错误。**Sed: -e表达式#1,字符43:未知选项' s'

除了在使用/作为分隔符时不转义/之外,您的模式不匹配,因为插入符号^断言字符串的开始部分将不匹配。

DEV-^[^0-9]*([0-9]+).*
----^

如果DEV-后面只能有数字,可以这样写:

echo "This is a test of DEV-1212" | sed -r 's~DEV-[0-9]+~<a href="https://devtest.net/&">&</a>~'

否则继续匹配非数字和该行其余部分:

echo "This is a test of DEV-1212" | sed -r 's~DEV-[^0-9]*[0-9].*~<a href="https://devtest.net/&">&</a>~'

输出
This is a test of <a href="https://devtest.net/DEV-1212">DEV-1212</a>

编辑

如果只匹配数字:

echo "This is a test of DEV-1212 with more data" | sed -r 's~DEV-[^0-9]*[0-9]+~<a href="https://devtest.net/&">&</a>~'

输出
This is a test of <a href="https://devtest.net/DEV-1212">DEV-1212</a> with more data

您没有转义/。为什么要转义"

echo "This is a test DEV-1212" | sed -r 's/DEV-^[^0-9]*([0-9]+).*/<a href="https://devtest.net/&">&</a>/'

,但使用不同的分隔符:

echo "This is a test DEV-1212" | sed -r 's|DEV-^[^0-9]*([0-9]+).*|<a href="https://devtest.net/&">&</a>|'

最新更新