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,
sed: sed stands for "stream editor" and it applies a search and replace regular expression (regex) to a list of files, if specified, or standard input (incoming text). Grep just searches, sed searches and replaces. xargs: This is more of a utility than a standalone command.
The -c flag to sh only accepts one argument while xargs is splitting the arguments on whitespace - that's why the double quoting works (one level to make it a single word for the shell, one for xargs).
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With