bash 用于查找和替换模式的 Unix sed 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14344972/
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 04:15:45  来源:igfitidea点击:

Unix sed command to find and replace a pattern

bashshellunixsed

提问by Lolly

I am trying to match the below pattern which has spaces in between.

我正在尝试匹配以下中间有空格的模式。

         -DsomeArg=some value 

and to replace it with below pattern using sed command.

并使用 sed 命令将其替换为以下模式。

         -DsomeArg="some value"

There can be any number of spaces in between. I tried below command but its not working.

之间可以有任意数量的空格。我试过下面的命令,但它不起作用。

          sed 's/^\(-D.*\)=(.\+\s\+.\+)/=""/' test.dat

where as .* works instead of .+ , but I want to match one or more pattern. I am not able to find what I am doing wrong. Please help me out.

其中 .* 工作而不是 .+ ,但我想匹配一个或多个模式。我无法找到我做错了什么。请帮帮我。

采纳答案by Adam Sznajder

cat /tmp/test | sed -r 's/^(-D.*?)=(.+\s+.+)/=""/'
-DsomeArg="some value"

Hope that will help :)

希望会有所帮助:)

回答by Rob Davis

This does what you asked for:

这可以满足您的要求:

sed 's/=\(.*\)/=""/'

or a little shorter:

或者更短一点:

sed 's/=/="/;s/$/"/'

But I have a feeling there's more to the story than you're saying. Like, are you expecting some text to follow "some value" that you want to leave outside of the quotation marks? Does something precede -DsomeArgthat you don't want to match?

但我有一种感觉,这个故事比你说的要多。例如,您是否希望某些文本跟随您想在引号之外留下的“某个值”?是否-DsomeArg有您不想匹配的内容?

With regular expressions, context is everything.

对于正则表达式,上下文就是一切。