-->

xargs: command substitution $(…) with pipe doesn&#

2020-06-03 07:36发布

问题:

I'm trying to write short script, and the following command:

echo "aaa111 bbb111" | xargs -I {} echo {} | sed 's/111/222/g'

returns aaa222 bbb222, which is what I expect.

I expected the next command:

echo "aaa111 bbb111" | xargs -I {} echo $(echo {} | sed 's/111/222/g')

to return the same, but it returns aaa111 bbb111! Why is that?


UPD: What I'm trying to achieve:

I have many files like pic30-coff-gcc, pic30-coff-ag, etc, and I need to make a symlink for each file, like pic30-gcc -> pic30-coff-gcc, etc.

So I wrote this:

ls|grep 'coff-'|xargs -I {} ln -s {} $(echo {} | sed 's/coff-//g')

It doesn't work: for each file, it reports that file exists. I checked the command like this:

ls|grep 'coff-'|xargs -I {} echo "ln -s {} $(echo {} | sed 's/coff-//g')"

And yep, the sed part doesn't work:

ln -s pic30-coff-gcc pic30-coff-gcc
ln -s pic30-coff-gcc-4.0.3 pic30-coff-gcc-4.0.3
...

But if I just type

echo "ln -s pic30-coff-gcc $(echo pic30-coff-gcc | sed 's/coff-//g')"

it works:

ln -s pic30-coff-gcc pic30-gcc

Then I've written test command with aaa111, and it doesn't work too. Still can't understand, why.

回答1:

It seems that all you need is a simple loop:

for file in *coff*; do
  ln -s "${file}" "${file/coff-/}"
done


回答2:

The for loop answer is exactly what I didn't come here to read. The whole purpose of xargs is avoiding this loop. xargs might not be the smartest tool for this particular case, but the question was about it.

Here is the solution I ended up with. It's probably not perfect, but works nevertheless :

echo "aaa111 bbb111" | xargs -I {} sh -c "echo \$(echo {} | sed 's/111/222/g')"
# Outputs aaa222 bbb222

You can come up with different variants of the same command :

echo "aaa111 bbb111" | xargs -I {} sh -c 'echo $(echo {} | sed "s/111/222/g")'
echo "aaa111 bbb111" | xargs -I {} sh -c "echo \`echo {} | sed 's/111/222/g'\`"

The main point here is just to invoke a new shell that will do the command substitution after xargs has replaced the replace-str(here {}) with the right content.



回答3:

$(echo {} | sed 's/111/222/g') is evaluated before it's passed to xargs as parameter. It will return "{}"

Hence:

echo "aaa111 bbb111" | xargs -I {} echo $(echo {} | sed 's/111/222/g')

is the same as

echo "aaa111 bbb111" | xargs -I {} echo {}