Rocky Li
Rocky Li

Reputation: 5958

Rename matching files based on a serial number

Assuming I have a bunch of files that are mac screenshots:

Screen Shot 2018-11-09 at 12.37.37 PM.png
Screen Shot 2018-11-10 at 4.53.02 PM.png
Screen Shot 2018-11-10 at 9.19.19 PM.png

And I want to use mv to label them to:

Screen_0.png
Screen_1.png
Screen_2.png

The partial command I come up with:

find . -name "Screen*" -exec sh -c 'mv "$1" "Screen_$2"' _ {} ??? \;

How to implement the command so that it can label image by digits? or do I have to resort to a more complicated file.

Upvotes: 1

Views: 262

Answers (4)

Mark Setchell
Mark Setchell

Reputation: 207455

You can just use rename, a.k.a. Perl rename:

rename --dry-run 's/.*/Screen_$N.png/' Screenshot*png

Sample Output

'Screenshot 2018-11-12 at 11.54.32.png' would be renamed to 'Screen_1.png'
'Screenshot 2018-11-12 at 11.54.38.png' would be renamed to 'Screen_2.png'
'Screenshot 2018-11-12 at 11.54.42.png' would be renamed to 'Screen_3.png'

If you like the look of the output, run again without --dry-run.


If you are on macOS, you can install Perl rename with homebrew:

brew install rename

Upvotes: 2

stack0114106
stack0114106

Reputation: 8711

With Perl one liner also, you could do it easily.

> ls -1 Screen*
Screen Shot 2018-11-09 at 12.37.37 PM.png
Screen Shot 2018-11-10 at 4.53.02 PM.png
Screen Shot 2018-11-10 at 9.19.19 PM.png
> perl -ne ' BEGIN { for(glob("Screen*")) {  rename "$_", "Screen_".$x++.".png" } ; exit }'
> ls -1 Screen*
Screen_0.png
Screen_1.png
Screen_2.png
>

Upvotes: 1

choroba
choroba

Reputation: 241848

If you use an array, no arithmetics is needed, just use the index of each element:

#!/bin/bash
files=('Screen Shot'*.png)
for i in "${!files[@]}" ; do
    mv "${files[i]}" Screen_$i.png
done

Upvotes: 1

codeforester
codeforester

Reputation: 42999

I don't think it is possible to pass a sequence number xargs in the way you want. Use a simple loop instead:

#!/bin/bash
for file in Screen*.png; do
  [[ -f $file ]] || continue # skip if not a regular file
  mv "$file" "Screen_$((count++)).png"
done

Upvotes: 2

Related Questions