Copy files from a numeric range to another folder

7

Slightly stumped on what CP command would copy files numbered 14 trough 39 into a directory called Volume2 from the following example:

01.mp3  04.mp3  07.mp3  10.mp3  13.mp3  16.mp3  19.mp3  22.mp3  25.mp3  28.mp3  31.mp3  34.mp3  37.mp3
02.mp3  05.mp3  08.mp3  11.mp3  14.mp3  17.mp3  20.mp3  23.mp3  26.mp3  29.mp3  32.mp3  35.mp3  38.mp3
03.mp3  06.mp3  09.mp3  12.mp3  15.mp3  18.mp3  21.mp3  24.mp3  27.mp3  30.mp3  33.mp3  36.mp3  39.mp3 
Volume2

user98496

Posted 2012-07-17T02:42:50.283

Reputation: 683

No cp command would do that. – Ignacio Vazquez-Abrams – 2012-07-17T02:48:02.960

cp {14..39}.mp3 Volume2 does it on my system...assuming the directory exists, of course. – user55325 – 2012-07-17T02:50:56.970

Answers

14

You could just do

cp {14..39}.mp3 Volume2

But the for-loop is handy for other things:

for f in {14..39}.mp3; do cp "$f" Volume2; done

user55325

Posted 2012-07-17T02:42:50.283

Reputation: 4 693

for the above example this wouldn't work for ranges including numbers below 10. For those you could do something like cp 0{1..9}.mp3 {10..39}.mp3 Volume2 – georg – 2015-10-30T13:00:07.683

@georg It works fine for me, in bash version 4.3.42 - what shell are you using? – user55325 – 2015-11-22T03:06:46.557

@user55325 I have got the same bash version as you have. Testing it again tells me that my solution is stupitely complicated. Just test these commands: echo {1..10}, echo {01..10} and echo {1..010}. (Just to make it more explicit: I am talking about the leading zeros-issue.) – georg – 2015-11-23T08:17:21.047

Ah, I understand. Yes, {01..39} should produce the desired range in that case. – user55325 – 2015-11-23T17:22:20.917

Not homework, though I am an on again/off again student focusing on Linux Admin. – user98496 – 2012-07-17T02:53:11.943

Awesome. Will give cp {14..39}.mp3 Volume2 a try. – user98496 – 2012-07-17T02:56:08.367

1Just for completion: the for-loop will have N cp invocations where N is the number of songs, as compared to the single invocation of the first example. Fewer invocations means faster and less resource intensive (in this simple case it doesn't matter in practice, though). A caveat is that if the expanded list exceeds ARG_MAX-1 (check value with getconf ARG_MAX, it is much higher than 39-14) number of entries, it will fail. Utilities such as xargs and find can take care of this caveat by splitting on ARG_MAX. – Daniel Andersson – 2012-07-17T08:37:02.437