Edwin Reyes
Edwin Reyes

Reputation: 97

how to rename multiple files in a multiples directories whit the name of each directory

i have a problem renaming all files in a folder, i found a simple solution to this here:

Rename files in multiple directories to the name of the directory

but what i notice is that it only works for single file within that folder, how can do it for multiples directories with multiple files inside each one

i have this example

test_folder/
   results_folder1/
     file_1.csv
     file_2.csv
     file_3.csv
     file_4.csv
     ...

   results_folder2/
     file_1.csv
     file_2.csv
     file_3.csv
     file_4.csv
     ...

to get this

test_folder/
   results_folder1/
     results_folder1_1.csv
     results_folder1_2.csv
     results_folder1_3.csv
     results_folder1_4.csv
     ...

   results_folder2/
     results_folder2_1.csv
     results_folder2_2.csv
     results_folder2_3.csv
     results_folder2_4.csv
     ...

I guess I can use rename, but how can made for this situation, thanks in advance for everyone

Upvotes: 1

Views: 79

Answers (1)

Z4-tier
Z4-tier

Reputation: 7978

You could loop over the result of find:

for f in $(find . -type "f" -printf "%P\n"); do
  mv $f $(dirname $f)/$(basename $(dirname $(readlink -f $f)) | tr '/' '_')_$(basename $f); 
done

explanation: recursively find all regular files, starting at the current directory, and print the relative path (one per line) without a leading ., storing it in a variable f. For each f, rename to [the directory portion of f]/[the basename of the directory name of f (ie. the name of the parent directory where f is located), with all / characters replaced by _]_[the filename potion of f]

Using find and the extra bit of complexity in $(dirname $f)/$(basename $(dirname $(readlink -f $f)) is to allow more than 1 level of nested directories.

Upvotes: 1

Related Questions