SKYCUBE.net

Solutions for Go, MySQL, PHP, Linux and more

Rename files via shell-script

Posted — Oct 28, 2009

In order to a miss configuration I had for a long time the problem with hundreds of

files which had a crap name. Tonight I had the time to solve this:

Preamble:

-rw------- 1 apache root 273K 24. Jul 15:37 UPLOAD_PATH1
-rw-r--r-- 1 apache root 275K 24. Jul 15:37 UPLOAD_PATH10
-rw-r--r-- 1 apache root 220K 19. Okt 15:14 UPLOAD_PATH11
-rw-r--r-- 1 apache root 3,1M 19. Okt 15:17 UPLOAD_PATH12
-rw-r--r-- 1 apache root 241K 19. Okt 16:13 UPLOAD_PATH13
-rw------- 1 apache root  60K 24. Jul 15:37 UPLOAD_PATH2
-rw------- 1 apache root 105K 24. Jul 15:37 UPLOAD_PATH3
-rw------- 1 apache root  60K 24. Jul 15:37 UPLOAD_PATH4
-rw------- 1 apache root  60K 24. Jul 15:37 UPLOAD_PATH5
-rw------- 1 apache root  60K 24. Jul 15:37 UPLOAD_PATH6
-rw------- 1 apache root  60K 24. Jul 15:37 UPLOAD_PATH7
-rw------- 1 apache root  60K 24. Jul 15:37 UPLOAD_PATH8
-rw-r--r-- 1 apache root 273K 24. Jul 15:37 UPLOAD_PATH9

The way to rename them is pretty simple with a bash script, but the notation/ syntax

is just a little bit tricky.

While searching with google, I’ve found several scripts but no simple solution.

My solution just executes a ls command, push the output in an array, and the builds a new name using sed.

After this steps, the new name is ready to use with a simple mv command.

Solution via bash:

#!/bin/bash
list=(`ls `)
for filename in "${list[@]}"
do
  myvar=$(echo $filename | sed 's/UPLOAD_PATH//g')
  #echo 'mv '$filename' '$myvar
  mv $filename $myvar
done