我有一个充满网址的文件,如下所示:
https://testing/this/string/for/now
我需要专门使用 sed 将它们全部替换为:
https://testing/this/now
并在最后保存更新内容的文件。所以实际上删除 无论“string”和“for”中存在什么内容(无论它们的长度如何),但保留 URL 的后一个“now”部分。
提前致谢。
文森特
最佳答案
您可以使用此 sed 命令删除 https://testing/this/
之后的 2 个路径:
sed -i.bak 's|\(https://testing/this/\)[^/]*/[^/]*/|\1|'' file
说明:
\(https://testing/this/\) # match and group https://testing/this/
[^/]*/ # match 0 or more of any character that is not /
[^/]*/ # match 0 or more of any character that is not /
作为替换,我们使用 \1
,它是对第一个捕获组的反向引用。
示例:
s='https://testing/this/string/for/now'
sed 's|\(https://testing/this/\)[^/]*/[^/]*/|\1|' <<< "$s"
https://testing/this/now
关于regex - 将文件中的部分 url 替换为 sed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643203/