PDA

View Full Version : [SOLVED] Regex File Rename



ided
June 1st, 2010, 09:41 PM
I am trying to wrap my head around regex and how it functions but am running into some issues getting a simple rename to perform the task I need.

I currently have the following filenames (sample)...
Discover_01_hi.mp4
02-Explore_hi.mp4
Discover-03_hi.mp4
(_hi will always be at the end)

I am trying to use rename to essentialy move _hi from the end and put hi_ at the beginning, for example the above filename results would be...
hi_Discover_01.mp4
hi_02-Explore.mp4
hi_Discover-03.mp4

I greatly appreciate any help you can provide.

roccivic
June 1st, 2010, 10:12 PM
Do you have to use regex?

Here's a bash script that does what you want:

#!/bin/bash

for file in *; do
if [ "`echo $file | grep _hi`" != "" ]; then
mv $file "hi_`echo $file | sed 's/_hi//'`"
fi
done

gmargo
June 1st, 2010, 10:29 PM
$ rename 's/^/hi_/' *_hi.mp4
$ rename 's/_hi\.mp4$/.mp4/' *_hi.mp4

ided
June 1st, 2010, 10:37 PM
Both answers worked like a charm and I can definitely use both of them. Thank you guys very much for your help!

sisco311
June 1st, 2010, 10:42 PM
You don't need two rename commands:

rename -n 's/(.*)_hi.mp4/hi_$1.mp4/' *_hi.mp4

ided
June 2nd, 2010, 06:58 PM
sisco311-

That worked perfect, thanks for your help as well!