Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use xargs with sed in search pattern

Tags:

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,

like image 908
Neuquino Avatar asked Jan 18 '13 16:01

Neuquino


People also ask

What is xargs sed?

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.

How do you pass arguments to xargs?

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).


2 Answers

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 
like image 86
Weetu Avatar answered Oct 14 '22 17:10

Weetu


this works on Linux(tested):

find . -type f -print0 | xargs -0 sed -i 's/str1/str2/g'  
like image 22
alex Avatar answered Oct 14 '22 18:10

alex