bash sed 替换所有字符直到第一个空格

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

Sed replace all characters until first space

regexbashsed

提问by nervosol

I am trying to replace some paths in config file. To do that I am trying to use sed.

我正在尝试替换配置文件中的一些路径。为此,我正在尝试使用 sed。

My file looks something like that:

我的文件看起来像这样:

-Djava.util.logging.config.file=/tmp/tmp/tmp/config bla.bla

I want to replace /tmp/tmp/tmp/configand keep bla.bla untouched. According to http://regexpal.com/and http://regexr.com?362qcI should use

我想替换/tmp/tmp/tmp/config并保持 bla.bla 不变。根据http://regexpal.com/http://regexr.com?362qc我应该使用

sed -e 's/logging.config.file=[^\s]+/logging\.config\.file\=\/new/g' file

sed -e 's/logging.config.file=[^\s]+/logging\.config\.file\=\/new/g' file

But it doesnt work.

但它不起作用。

采纳答案by fedorqui 'SO stop harming'

This will replace /tmp/tmp/...with aaa:

这将替换/tmp/tmp/...aaa

$ sed 's/\(.*=\)[^ ]* \(.*\)/ aaa /g' <<< "-Djava.util.logging.config.file=/tmp/tmp/tmp/config bla.bla"
-Djava.util.logging.config.file= aaa bla.bla

It "saves" anything up to =in \1. Then fetches everything up to an space. Finally "saves" the rest of the string in \2.

它“保存”任何东西直到=in \1。然后将所有内容提取到一个空间。最后将字符串的其余部分“保存”在\2.

The replacement is done by echoing \1+ "new string" + \2.

替换是通过 echo \1+ "new string" + 完成的\2

回答by choroba

\sis not supported by sed. Also, the +must be backslashed to get its special meaning. I would also backslash the dots to prevent them from matching anything:

\s不支持sed。此外,+必须反斜杠才能获得其特殊含义。我还会反斜杠点以防止它们匹配任何内容:

sed -e 's/logging\.config\.file=[^[:space:]]\+/logging\.config\.file\=\/new/g'

or, shorter

或者,更短

sed -e 's%\(logging\.config\.file=\)[^[:space:]]\+%/new%g'