Skip to content
Advertisement

linux how to change a file name to the name of its folder?

I’m working in Linux, I have a folder that contains many sub-folders, in each sub-folder there is a file named Analyze.txt. I would like to move all these files (Analyze.txt) into one folder and change the name of the file Analyze.txt to the name of the sub-folder it originated from.

Thanks,

Raz

Advertisement

Answer

Create a bash script .sh and give it the right permission

chmod +x <file>.sh

Let see the code to write into the script. First of all move to the root directory:

cd <path-to-root>

Now you need to loop each sub-folder, rename the file in and then move it to destination directory:

for dir in `ls`; do
    if [[ -d $dir ]]; then
        cd $dir
        mv ./Analyze.txt ./$dir.txt
        mv ./$dir.txt <path-to-dest-directory>
        cd ..
    fi
done

With this code i supposed that the destination directory is not in the root of your tree.

Advertisement