Search code examples
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
    
    • Find all *.txt files inside the Origin directory, separate with NUL instead of spaces just in case the file names have spaces in them
    • Pipe the result into the loop, reading record by record, making sure to cut records by the NUL byte
    • name is after the first slash
    • destination_name has Destination prepended, and all slashes in name changed to underscores
    • print out the CSV row
    • copy the file

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