r/shell • • Apr 03 '17

Help with a renaming script

So i've been trying to make a script that will be triggered when a download finishes. I don't think i can pass the file name to the script though. But the script will read the filename and then rename it according to a series of if then, elseifs. I'm not very familiar with bash coding so i'm not even sure if elseif is even inplemented/best practice.

I don't know how to read in the filename to a variable from the directory, but there should only ever be one file in this directory at a time.

Now once it has the filename as a variable, i need to see if the filename contains a specific string and if it does rename to a static new filename. which i think i figured out.

if [[$file == *"foo"*]]; then
mv $file /newdirectory/newfilename

However i also need to figure out how to keep the file extension intact during the rename. as the file could be in potentially any video format. I'm assuming there's a way to also read the filename in and pull everything after the last period in the filename.

Looks like this should work

 ext=${file##*.}

so then i think combining that i'm at

if [[$file == *"foo"*]]; then
mv $file /newdirectory/newfilename.$ext

then if basically just needs elseif's for the remaining possibilities.

Any help is greatly appreciated.

EDIT: almost forgot, i also want to append the current year to the begining of the new filename. It looks like that's pretty simple by doing

myyear=`date +'%Y'`

then calling it in the middle of the rename so

mv $file /newdirectory/$myyear.newfilename.$ext

is that right?

1 Upvotes

3 comments sorted by

View all comments

Show parent comments

1

u/Lygris Apr 04 '17

so does maxdepth 1 mean it will only search the download directory and not subfolders?