Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I've got a directory with numbered files, e.g. 1_foo.txt 2_bar.asc 13_test.png, and want to move them into individual directories (e.g. 1, 2 and 13) using as simple a bash command as possible.

Creating the numbered directories was easy:

mkdir $(seq 1 15)

I've also come up with a command to copy the files into their respective directories:

seq 15 -1 1 | xargs -I@ mv @_* @

That doesn't work, though, as the * is interpreted as a normal character when used with xargs, giving me errors like "mv: File '15_*' not found.".

Is there any easy way to use * as a wildcard in a command called by xargs?

share|improve this question

2 Answers 2

up vote 7 down vote accepted

You were very close.

seq 15 -1 1 | xargs -I@ sh -c "mv @_* @"

You need to delay the interpretation (expansion) of the * until after the @ substitution has occurred.  (But you already understood that that was the problem, right?)

share|improve this answer
    
Thanks, that worked perfectly. I'll vote your answer up as soon as I've got enough reputation to do that. –  n.st Dec 13 '12 at 19:48

Just don't use xargs for that. Use a for loop:

for i in $(seq 1 15); do
    mv ${i}_* $i
done

Even better is to use brace expansion instead of seq:

mkdir {1..15}

for i in {1..15}; do
    mv ${i}_* $i
done
share|improve this answer
    
You're right, that's definitely more elegant than using xargs. Thanks for telling me about brace expansion. –  n.st Dec 13 '12 at 19:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.