Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.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_Awk_Sed - Fatal编程技术网

如何在BASH中删除{}括号之外的所有内容?

如何在BASH中删除{}括号之外的所有内容?,bash,awk,sed,Bash,Awk,Sed,我需要删除出现在{和}括号外的所有数据。例如,这是一行$variable: The fish {{went}} to the {{restaurant}} to eat some {fish} for lunch. 在删除配对的{和}之外的所有内容后,输出将为: {{went}}{{restaurant}}{fish} 所有大括号成对出现 我找到了一篇类似的帖子,它涉及方括号,但我试图修改这两个答案的尝试失败了,因为[和{在代码中可以有多种含义,既可以作为原始数据中显示的符号,也可以作为

我需要删除出现在
{
}
括号外的所有数据。例如,这是一行
$variable

The fish {{went}} to the {{restaurant}} to eat some {fish} for lunch.
在删除配对的
{
}
之外的所有内容后,输出将为:

{{went}}{{restaurant}}{fish}
  • 所有大括号成对出现
我找到了一篇类似的帖子,它涉及方括号,但我试图修改这两个答案的尝试失败了,因为
[
{
在代码中可以有多种含义,既可以作为原始数据中显示的符号,也可以作为
sed
awk
或正则表达式使用。根据另一篇文章中的答案,我尝试了这一点

awk -F '\{\}\{\}' '{for (i=2; i<NF; i+=2) printf "[%s]%s", $i, OFS; print ""}' <<< "$variable"

sed -e 's/^[^\{]*//;s/\}[^\{]*\[/\} \[/g;s/[^{]*$//;' <<< "$variable"

awk-F'\{\}'{for(i=2;i这里有一个使用grep的解决方案,-p意味着使用Perl语法,它允许非贪婪表达式,-o只打印匹配项

echo "The fish {{went}} to the {{restaurant}} to eat some {fish} for lunch." |
grep -Po '{?{[^{}]+}}?'
或使用GNU awk进行FPAT:

$ echo "The fish {{went}} to the {{restaurant}} to eat some {fish} for lunch." |
gawk -v FPAT='{[^}]+}+' -v OFS= '{$1=$1}1'
{{went}}{{restaurant}}{fish}

下面是使用vanilla
sed
的另一种方法:

sed 's/^[^{]*\|[^}]*$//g; s/}[^{}]*{/}{/g' <<< "$variable"

派对有点晚了。这里有一个
perl
解决方案

perl -ne'print for /{[^}]+}+/g'
或者,如果你喜欢在末尾加一条新的线,那么

perl -ne'print for /{[^}]+}+/g }{ print "\n"'
这可能适用于您(GNU-sed):

或:

假设所有
{
}
是平衡的


注意:这避免了交替。

括号会被嵌套吗?例如,{quick brown{{fox}}跳到懒狗身上。{quick brown{{fox}}}不会,它们从来没有像你所说的那样嵌套。另一个例子:
deleted{not deleted}deleted{not deleted}删除了
。只是要确保这是一个更难的问题。把它放在一行,管道到
|粘贴-sd'
做得好。它同样适用于
'鱼{{去了}餐厅}吃了一些{鱼}和{薯条}和{喝了}很多{威士忌作为午餐。
{{薯片}{{饮料}{威士忌}
perl -ne'print for /{[^}]+}+/g'
perl -ne'print for /{[^}]+}+/g }{ print "\n"'
$ echo "The fish {{went}} to the {{restaurant}} to eat some {fish} for lunch." | 
perl -ne'print for /{[^}]+}+/g }{ print "\n"'
{{went}}{{restaurant}}{fish}
sed 's/[^{]*\(\({{*[^}]*}}*\)*\)/\1/g' file
sed -r 's/[^{]*((\{+[^}]*\}+)*)/\1/g' file