1

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

  • 1
    Wrap the linked solution inside a loop (e.g. `for top in dir1 dir2 ...; do (cd "$top"; linked_solution_here); done` to apply it to each of the top directories. Add your attempts to your question if you get stuck with that. If you succeed, you can add and accept your own answer. – Socowi Dec 18 '20 at 00:16
  • ok i will try a for loop,thanks mate – Edwin Reyes Dec 18 '20 at 00:17

1 Answers1

1

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.

Z4-tier
  • 7,287
  • 3
  • 26
  • 42