bash 如何在搜索模式中使用 xargs 和 sed

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

how to use xargs with sed in search pattern

bashsedreplacepipeline

提问by Neuquino

I need to use the output of a command as a search pattern in sed. I will make an example using echo, but assume that can be a more complicated command:

我需要使用命令的输出作为 sed 中的搜索模式。我将使用 echo 做一个例子,但假设这可能是一个更复杂的命令:

echo "some pattern" | xargs sed -i 's/{}/replacement/g' file.txt

That command doesn't work because "some pattern" has a whitespace, but I think that clearly illustrate my problem.

该命令不起作用,因为“某种模式”有空格,但我认为这清楚地说明了我的问题。

How can I make that command work?

我怎样才能使该命令起作用?

Thanks in advance,

提前致谢,

采纳答案by Steve

Use command substitution instead, so your example would look like:

改用命令替换,因此您的示例如下所示:

sed -i "s/$(echo "some pattern")/replacement/g" file.txt

The double quotes allow for the command substitution to work while preventing spaces from being split.

双引号允许命令替换起作用,同时防止空格被拆分。

回答by Weetu

You need to tell xargs what to replace with the -I switch - it doesn't seem to know about the {} automatically, at least in some versions.

您需要告诉 xargs 用 -I 开关替换什么 - 它似乎并不自动了解 {},至少在某些版本中。

echo "pattern" | xargs -I '{}' sed -i 's/{}/replacement/g' file.txt

回答by alex

this works on Linux(tested):

这适用于 Linux(已测试):

find . -type f -print0 | xargs -0 sed -i 's/str1/str2/g' 

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

echo "some pattern" | sed 's|.*|s/&/replacement/g|' | sed -f - -i file.txt

Essentially turn the some patterninto a sed substitution command and feed it via a pipe to another sed invocation. The last sed invocation uses the -fswitch which accepts the sed commands via a file, the file in this case being the standard input -.

基本上将some patternsed 转换为 sed 替换命令,并通过管道将其提供给另一个 sed 调用。最后一次 sed 调用使​​用-f通过文件接受 sed 命令的开关,在这种情况下,该文件是标准输入-

If you are using bash, the here-stringcan be employed:

如果您使用的是 bash,则here-string可以使用:

<<<"some pattern" sed 's|.*|s/&/replacement/g|' | sed -f - -i file.txt

N.B. the sed separators |and /should not be a part of some patternotherwise the regexp will not be formed properly.

注意 sed 分隔符|/不应成为其中的一部分,some pattern否则将无法正确形成正则表达式。