[Bash]: Change Multiple File Names on Terminal

bash

05/09/2019


TL;DR

BASH
n=1; for file in *; do mv "$file" "$n.jpg"; let n++; done

Overview

While working on a new project, game TwentyOne, I encountered a situation where I needed to change a multiple files more conveniently.

To animate an image in Swift, it is better to follow a name convention to put image files to an array.

On Bash

For example, I would like to change name of files to diceLayer1.png ~ diceLayer2.png

Former Approach

By using wildcard, I believed changing *\${i}.png to diceLayer\${i}.png would solve the problem. However, *1.png would include filename1.png* AND filename11.png

Final solution

Use \*-\${i}.png instead as a source for mv command
Bash command:

BASH
for i in {1..17}; do mv *-${i}.png diceLayer${i}.png; done
BASH
*-${i}.png diceLayer${i}.png

This changes all files that ends with name, -1.png ... -17.png to diceLayer1.png ... diceLayer17.png

Result

Caveat

There is no native function in linux terminal to revert your command line, so be cautious

Changing multiple images to 1.jpg, 2.jpg, 3.jpg ...

In the directory folder, type in following command

BASH
n=1; for file in *; do mv "$file" "$n.jpg"; let n++; done

WRITTEN BY

Keeping a record