how to use xargs with sed in search pattern

十年热恋 提交于 2019-12-03 02:03:33

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.

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.

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

this works on Linux(tested):

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

This might work for you (GNU sed):

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

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

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

<<<"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 pattern otherwise the regexp will not be formed properly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!