linux - 匹配两个或模式并交换所有模式的文本

标签 linux sed

我有一个问题,我需要将一个站点的标记更改为另一个站点。 首先,我有这种类型的: [[https://stackoverflow.com/][StackOverflow]],我需要将其更改为 [StackOverflow|https://stackoverflow.com/]

我的 sed 命令是

sed -i 's/\[\[\(.*\)\]\[\(.*\)\]\]/\[\2|\1\]/g' 

这仅在我有一个匹配模式时才有效,否则它会崩溃。我应该改变什么?

最佳答案

您可以使用 [^][] 否定括号表达式匹配任何 0 个或多个字符:

sed -i 's/\[\[\([^][]*\)\]\[\([^][]*\)]]/[\2|\1]/g' file

参见 online sed demo :

s="Text [[https://stackoverflow.com/][StackOverflow]] More text [[https://stackoverflow2.com/][StackOverflow2]]"
sed 's/\[\[\([^][]*\)\]\[\([^][]*\)]]/[\2|\1]/g' <<< "$s"

输出:

Text [StackOverflow|https://stackoverflow.com/] More text [StackOverflow2|https://stackoverflow2.com/]

关于linux - 匹配两个或模式并交换所有模式的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55022032/

相关文章:

php - 访问 htdocs 文件夹外的 html 文件/视频文件

linux - 使用 awk/sed/bash 检索所有必需字段后打印

linux - 使用 sed 删除文件中的行,但定义的多个模式除外

c - 解析要上传到 Google 日历的时间表

c - 我想知道 struct FILE 的内部成员,最新的

linux - grep:字符类语法是 [[:space:]],而不是 [:space:]

php - 使用 PHP 问题的 AWS LAMP Stack 连接到 MySQL 数据库

linux - 如何将 linux 系统文件覆盖到 yocto 文件系统中?

c - 什么是换行符—— '\n'

shell - 仅当在 sed 中匹配时才打印特定行号