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:
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,
Use command substitution instead, so your example would look like:
The double quotes allow for the command substitution to work while preventing spaces from being split.
This might work for you (GNU sed):
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:N.B. the sed separators
|
and/
should not be a part ofsome pattern
otherwise the regexp will not be formed properly.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.
this works on Linux(tested):