regex - 将文件中的部分 url 替换为 sed

标签 regex sed command-line

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

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/

相关文章:

regex - 在 Go 中获取正则表达式的解析树

javascript - Google Apps 脚本正则表达式匹配第 n 次出现

PHP - 解析、正则表达式 CSS 文件?

matlab - 使用多行命令调用 Matlab 历史

系统配置目录的 Windows 等价物

bash - 在 bash 中将十六进制字节发送到串行

c# - 计算与字符串中的模式匹配的标记数

xml - 转换仅包含特定标签的 xml

linux - 如何在 Linux 中使用 lynx/w3m 提取多个 URL 的文本

bash - 使用 Bash 在特定行之前插入多行文本