Skip to Content
Linux Shell Scripting Cookbook - Third Edition
book

Linux Shell Scripting Cookbook - Third Edition

by Clif Flynt, Sarath Lakshman, Shantanu Tushar
May 2017
Beginner
552 pages
28h 47m
English
Packt Publishing
Content preview from Linux Shell Scripting Cookbook - Third Edition

How to do it...

The following script uses find to locate PNG and JPEG files, then uses the ## operator and mv to rename them as image-1.EXT, image-2.EXT, and so on. This changes the file's name, but not its extension:

#!/bin/bash 
#Filename: rename.sh 
#Desc: Rename jpg and png files 

count=1; 
for img in `find . -iname '*.png' -o -iname '*.jpg' -type f -maxdepth 1` 
do 
  new=image-$count.${img##*.} 

  echo "Renaming $img to $new" 
  mv "$img" "$new" 
  let count++ 

done  

The output is as follows:

$ ./rename.sh
Renaming hack.jpg to image-1.jpg
Renaming new.jpg to image-2.jpg
Renaming next.png to image-3.png

The preceding script renames all the .jpg and .png files in the current directory to new filenames in the format image-1.jpg, image-2.jpg, image-3.png ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Linux Shell Scripting - Second Edition

Mastering Linux Shell Scripting - Second Edition

Mokhtar Ebrahim, Andrew Mallett

Publisher Resources

ISBN: 9781785881985