1

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?

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.