Thursday, October 6, 2022

[SOLVED] Organizing different files with a naming convention?

Issue

I just finished a short lesson into linux cli and I'm trying to use cli as a way to organize & tidy up my files within directories.

The files are of varying format (.png, .jpg, .mp4, .txt, ...) with long string names that doesn't even relate to the file.

My objective is to rename all of them (regardless of extension type) with a common name & attach a number based on their order count. (while keeping the extension type untouched)

Example:
blahblah1234_4312.txt, randompic-2022-14-15.jpg, logo_3355234234.png, slowmovideo_2020-31-06.mp4

renamed into:
droneProject_1.txt, droneProject_2.jpg, droneProject_3.png, droneProject_4.mp4

I'll be doing the same process on other directories so I figured I needed to make a bash script that takes the desired common name as the $1 and the chosen directory as $2.

I have an idea what to tell the script to do but I don't know how to code it properly, so far here's my attempt; (it's pseudo code...i think)

for file in $2
do
    orderCount=1
    mv $singleFile $1_$orderCount.keepExtensionType
    orderCount=+1
done

It may seem I have no idea what i'm doing but to me that pseudo code makes sense...help


Solution

the trick is ${f##*.} to extract the filename extension. the rest is straightforward(?).

#!/bin/bash

count=1

for f in $2/* ; do
    EXT=${f##*.}
    mv $f $1_${count}.${EXT}
    count=$(( $count + 1 ))
done


Answered By - Mars Z'uh
Answer Checked By - Pedro (WPSolving Volunteer)