In the past when I’ve needed to automate a task, such as renaming thousands of files, I’ve tended to use the Python OS module. However, lately I’ve started to write Bash scripts to achieve these tasks, because of how quickly and easily it allows me to work within the Unix filesystem. Last week, one of my programs produced thousands of images with random names. I decided that I needed to write a script to rename all the jpg files in a directory incrementing from 0:
#!/bin/sh increment=0 #for i in $(ls); do for i in *.jpg; do mv "$i" "$increment.jpg" echo $increment increment=$[increment+1] done
This script loops over every jpg file, and with each loop, the variable “increment” has 1 added to it by the “increment=$[increment+1]” statement. This resulted in a directory full of jpg files named 0.jpg, 1.jpg, 2.jpg… etc.