TransWikia.com

Rename Files in Directory Appending Three Digit Numbers and Spaces and Varying Extensions via Terminal

Unix & Linux Asked by ksnowdayz on February 14, 2021

I have a list of files in a directory that display like this via an ls command:

01-Campout 2001.jpg
2-Campout 2001.png
Campout 2001 - 3 of 21.tiff
Campout 2001 - 4.pdf

I would like to know what bash command I could use to remove the current numbering and replace it with a naming convention that has a three-digit number count at the beginning while preserving the text afterward to include the space between Campout and 2001. This has a mix of .jpeg and .png files.

What I would like the end result to look like:

001-Campout 2001.jpg
002-Campout 2001.png
003-Campout 2001.tiff
004-Campout 2001.pdf

Thanks so much

One Answer

With zsh:

$ autoload -Uz zmv # best in ~/.zshrc
$ zmv -n '((<1-999>)-(*)|(*) - (<->) of <->(.*)|(*) - (<->)(.*))' '${(l[3][0])${:-$2$5$8}}-$3$4$6$7$9'
mv -- '01-Campout 2001.jpg' '001-Campout 2001.jpg'
mv -- '2-Campout 2001.png' '002-Campout 2001.png'
mv -- 'Campout 2001 - 3 of 21.tiff' '003-Campout 2001.tiff'
mv -- 'Campout 2001 - 4.pdf' '004-Campout 2001.pdf'

(remove -n (for dry-run) if happy).

Answered by Stéphane Chazelas on February 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP