Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a list of files with consecutive numbers as suffixes. I would like to copy only a range of these files. How can I specify a range as part of my cp command.

$ls
P1080272.JPG* P1080273.JPG* P1080274.JPG* P1080275.JPG* P1080276.JPG* P1080277.JPG*
P1080278.JPG* P1080279.JPG* P1080280.JPG* P1080281.JPG* P1080282.JPG* P1080283.JPG*

I would like to copy files from P1080275.JPG to P1080283.JPG with something similar to:

$cp P10802[75-83].JPG ~/Images/.

Is there a way to do this?

share|improve this question
up vote 10 down vote accepted

Very close:

cp P10802{75..83}.JPG ~/Images
share|improve this answer
    
Why do you say very close? Because that worked exactly like how I wanted. Am I missing any pitfalls? – Amjith Mar 16 '12 at 20:24
3  
I meant that your question was almost the correct syntax. You were very close. – glenn jackman Mar 16 '12 at 20:27

To iterate over a range in bash:

for x in {0..10}; do echo $x; done

Applying the same in your case:

for x in {272..283}; do cp P1080$x.JPG ~/Images; done
share|improve this answer
    
This does work, but I like @glenn jackman's answer better since it doesn't invoke any programming construct. – Amjith Mar 16 '12 at 20:25

Zsh, with the extendedglob option has the globbing (pattern matching) operator.

setopt extendedglob
echo P10802<75-83>.JPG

will match filenames in the current directory that match that pattern (beware that P1080275.JPG matches but so does P108020000000075.JPG)

On the other end, the {x...y} string expansion operator (supported by zsh and recent versions of bash and ksh93), expands to the strings from x to y, regardless of what files there are in the current directory.

cp P10802<75-83>.JPG ~there

will copy the matching files, so will

cp P10802{75..83}.JPG ~there

But you'll get errors if for instance P1080281.JPG doesn't exist.

share|improve this answer

Would this work for you:

for each in {75..83}; do cp P10802$each.JPG ~/Images/; done
share|improve this answer

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.