用文件中的 sed 替换部分 url [英] replace parts of url with sed in a file

查看:137
本文介绍了用文件中的 sed 替换部分 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个充满网址的文件,如下所示:

I have a file full of urls that looks like this:

https://testing/this/string/for/now

我需要专门使用 sed 将它们全部替换为:

which I need to have them all replaced using sed specifically, to:

https://testing/this/now

并在最后保存带有更新内容的文件.所以实际上删除'string' 和 'for' 中存在的任何内容(无论它们的长度如何),但保留后一个 'now' 部分的 url.

and save the file at the end with the updated content. So actually remove whatever content exists in the 'string' and 'for'(no matter their length might be), but keep the latter 'now' part of the url.

提前致谢.

文森特

推荐答案

你可以使用这个 sed 命令删除 https://testing/this/ 后的 2 个路径:

You can use this sed command to remove 2 paths after https://testing/this/:

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,它是对第一个捕获组的反向引用.

In replacement we're using \1 which is back-reference to first capturing group.

示例:

s='https://testing/this/string/for/now'
sed 's|\(https://testing/this/\)[^/]*/[^/]*/|\1|' <<< "$s"
https://testing/this/now

这篇关于用文件中的 sed 替换部分 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆