bashcsvfilerename

How to copy all files with specific extension and rename them adding the subdirectory names


I have a folder Bash with two subdirectories Origin and Destination.

Origin has subdirectories 1, 2, 3, 4. Each of them has its own subdirectories. For example, 1 has subdirectories 11, 12, 13 ,etc. 2 has subdirectories 21, 22, 23, etc.

The directory 11 has files 1.txt, 2.txt, 3.txt and files with other extension. The directory 12 has different .txt files but with the same names 1.txt, 2.txt, 3.txt and files with other extension as well.

In fact, every final subdirectory (e.g. 11, 12, 13, 21, 22, ...) has text files with the same name.

  1. How do I copy all text files from Origin to Destination, but because all file names are the same, with changing the names, including the subdirectories name where they come from? For example, 1.txt from 11 subdirectory will have a name 1_11_1.txt in Destination and 1.txt from 23 subdirectory will have 2_23_1.txt name.

  2. How do I create .csv file in the Destination with all the original file names, their original location and their new file names?

Could you please explain the process of your thinking, how you create such bash script?

Thank you!


Solution

  • find Origin -name "*.txt" -print0 |
    while IFS= read -r -d '' origin_name
    do
      name="${origin_name#*/}"
      destination_name="Destination/${name//\//_}"
      echo '"'"$origin_name"'","'"$destination_name"'"'
      # cp "$origin_name" "$destination_name"
    done
    

    EDIT: Got beaten by a hair, but still I think there's value