Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在BASH中,如何将匹配`{+(任意)+}`的模式替换为`{+(任意)+:+(任意)+}`的模式?_Bash_Sed - Fatal编程技术网

在BASH中,如何将匹配`{+(任意)+}`的模式替换为`{+(任意)+:+(任意)+}`的模式?

在BASH中,如何将匹配`{+(任意)+}`的模式替换为`{+(任意)+:+(任意)+}`的模式?,bash,sed,Bash,Sed,我有一个包含一些文本的文件,其中一些重要项目用大括号开头和结尾标记,例如: Once upon a {time}, there lived a rabbit. The {rabbit lived} in a small house. One day, the {rabbit visited }the {mountains}. In the mountains, he {found} a tree with 10{,000} branches. 我需要用{x::x}替换{x}形式中的任何项,例如

我有一个包含一些文本的文件,其中一些重要项目用大括号开头和结尾标记,例如:

Once upon a {time}, there lived a rabbit.
The {rabbit lived} in a small house.
One day, the {rabbit visited }the {mountains}.
In the mountains, he {found} a tree with 10{,000} branches.
我需要用{x::x}替换{x}形式中的任何项,例如:

每个开口{在同一行上都有一个匹配的}。 大括号永远不会跨线拆分。 大括号从不嵌套。 任何类型的符号都可能出现在{和}之间。 我尝试了几种sed方法,但均无效,例如:

sed 's/{(.*)}/{&::&}/g' file.txt
如何用模式{some word::some word}替换大括号中的所有项,例如{some word}?

这里是修复方法

sed 's/{\([^}]*\)}/{\1::\1}/g' file

Once upon a {time::time}, there lived a rabbit.
The {rabbit lived::rabbit lived} in a small house.
One day, the {rabbit visited ::rabbit visited }the {mountains::mountains}.
In the mountains, he {found::found} a tree with 10{,000::,000} branches.
解释 [^}]*匹配非}字符 \…\将捕获参数内指定的字符,并且\1将用于引用第一个匹配项,这是正则表达式的一部分。 你应该使用

sed 's/\([^{]*{\)\([^}]*\)\(}.*\)/\1\2::\2\3/'

未经测试

如果可以使用perl,则会更容易:

它匹配大括号{…}非贪婪中的所有内容,然后用所需字符串{$1::$1}替换它。

awk variant:


将只在有1{}的字符串上工作,并且您需要使用许多字符,而不需要对@BMW solution进行太多的查看。当RS是正则表达式时,有没有办法使用ORS=RS?我只想使用{或}而不是[{}]?与其他答案相比,它的一个优点可能对当前输入不是很有用,但仍然..:如果{}中的文本包含一个嵌入的新行,它也被处理。
sed 's/\([^{]*{\)\([^}]*\)\(}.*\)/\1\2::\2\3/'
$ perl -ple 's/{(.*?)}/{$1::$1}/g' file
Once upon a {time::time}, there lived a rabbit.
The {rabbit lived::rabbit lived} in a small house.
One day, the {rabbit visited ::rabbit visited }the {mountains::mountains}.
In the mountains, he {found::found} a tree with 10{,000::,000} branches.
$ awk 'BEGIN{ORS=""} NR%2==0{$0="{"$0"::"$0"}"} 1' RS='[{}]' file.txt

Once upon a {time::time}, there lived a rabbit.
The {rabbit lived::rabbit lived} in a small house.
One day, the {rabbit visited ::rabbit visited }the {mountains::mountains}.
In the mountains, he {found::found} a tree with 10{,000::,000} branches.