# Rename files in group

I've folder and file structure like


Folder/1/fileNameOne.ext
Folder/2/fileNameTwo.ext
Folder/3/fileNameThree.ext
...


How can I rename the files such that the output becomes


Folder/1_fileNameOne.ext
Folder/2_fileNameTwo.ext
Folder/3_fileNameThree.ext
...


How can this be achieved in linux shell?

-
also asked on stackoverflow –  glenn jackman Apr 11 '13 at 21:44
Look for 'rename' command, that support regexp rename askubuntu.com/questions/175281/… –  hute37 Apr 16 '13 at 14:43

Here is a bash script that does that:

Note: This script does not work if any of the file names contain spaces.

#! /bin/bash

# Only go through the directories in the current directory.
for dir in $(find ./ -type d) do # Remove the first two characters. # Initially,$dir = "./directory_name".
# After this step, $dir = "directory_name". dir="${dir:2}"

# Skip if $dir is empty. Only happens when$dir = "./" initially.
if [ ! $dir ] then continue fi # Go through all the files in the directory. for file in$(ls -d $dir/*) do # Replace / with _ # For example, if$file = "dir/filename", then $new_file = "dir_filename" # where$dir = dir
new_file="${file/\//_}" # Move the file. mv$file $new_file done # Remove the directory. rm -rf$dir
done

• Copy-paste the script in a file.
• Make it executable using
chmod +x file_name

• Move the script to the destination directory. In your case this should be inside Folder/.
• Run the script using ./file_name.
-
Thank You very much :-) –  TheKojuEffect Apr 11 '13 at 15:50