从字符串 bash 中删除一个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25638938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:17:26  来源:igfitidea点击:

Remove a word from a string bash

bash

提问by Ciprian Vintea

I have the string

我有字符串

file="this-is-a-{test}file" 

I want to remove {test}from this string. I used

我想{test}从这个字符串中删除。我用了

echo $file | sed 's/[{][^}]*//'  

but this returned me

但这让我回来了

this-is-a-}file

How can I remove }too?

我也怎么去掉}

Thanks

谢谢

回答by Shinnok

Also try this bash only oneliner as an alternative:

也可以试试这个 bash only oneliner 作为替代:

s="this-is-a-{test}file"
echo ${s/\{test\}/}

回答by anubhava

You can use sedwith correct regex:

您可以使用sed正确的正则表达式:

s="this-is-a-{test}file"
sed 's/{[^}]*}//' <<< "$s"
this-is-a-file

Or this awk:

或者这个 awk:

awk -F '{[^}]*}' '{print  }' <<< "$s"
this-is-a-file