'xargs with args from echo and -I {} doesn't appear to work...?

I try to use xargs with both -n 1 and -I {} at the same time, but with no success...

Let's say you want to move 1.txt 2.txt 3.txt to other names:

for i in 1 2 3; do
    mv ${i}.txt ${i}_ren.txt
done

now I try to pass the 1 2 3 values to xargs via echo, but it does not appear to work. I use:

echo 1 2 3 | xargs -n 1 -I {} mv {}.txt {}_ren.txt

What am I doing wrong?



Solution 1:[1]

It seems impossible to combine xargs options -n and -I ,

see e.g. https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=31858&gt

However it is possible to use only one pipe instead of

echo 2 3 4 | xargs -n 1 | xargs -I {} mv {}.txt {}_ren.txt

to achieve the same effect.

For this the newline at the end of the echo output has to be disabled (system-dependent); using space as delimeter for xargs:

echo -n 2 3 4 | xargs -d " " -I {} mv {}.txt {}_ren.txt

Unfortunately this solution is probably not less intricated.

Solution 2:[2]

What am I doing wrong?

You are doing wrong because -I is for each input line.

You can either replace space with new line by:

echo 1 2 3 | tr ' ' '\n' | xargs -I {} -P0 mv {}.txt {}_ren.txt

or use seq instead of echo by:

seq 3 | xargs -I {} -P0 mv {}.txt {}_ren.txt

or without -I by

echo 1 2 3 |
  tr ' ' '\n' |
  sed 's/.*/&.txt &_ren.txt/' |
  xargs -n2 -P0 mv

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Weihang Jian