xargs: command substitution $(…) with pipe doesn't work

风格不统一 提交于 2020-05-25 04:46:08

问题


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 {}


来源:https://stackoverflow.com/questions/22589438/xargs-command-substitution-with-pipe-doesnt-work

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