Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

bash - xargs: command substitution $(...) with pipe doesn't work

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...