I have several files which were recovered from a backup but have the structure (file location) as the file name.


F\New folder\concerts\0904M002.WAV

I want to make a script that takes these names one by one and creates the respective folders and place the file inside the folder.

for eg: F\New folder\concerts\0904M002.WAV

--> Make a folder "F" on current directory then cd to F make a folder "New folder" similarly make "concerts" (or directly do mkdir F\New folder\concerts)

--> rename the file "F\New folder\concerts\0904M002.WAV " to "0904M002.WAV " and move it to the newly created folder "F\New folder\concerts\"

Can some one help me with the script? Thanks

  • Those files were backed up from windows but i am on linux. it was done with a program that packs all files into a zip renaming each file for their path. i have forgotten the name of the program so now i have to manually extract the zip and rename the file and move them into their respective folders . – Ashwin Kumar k Oct 13 '16 at 7:59
  • Ok, I believe you :) – Jacob Vlijm Oct 13 '16 at 8:01

Use the following bash script.

for file in *\\*
    [ -d "$destFolder" ] || mkdir -p "$destFolder"
    mv -v "$file" "$destFile"

The code basically replaces all the \ in the source file with / to get the destination file path. Then it gets the destination directory of the file and creates it using mkdir -p. Finally the file is copied to the destination folder.

Write the code into a file (let us say script.sh) and then in terminal do

$ chmod +x script.sh
$ ./script.sh
  • 2
    No need to use sed since Bash has pattern substitution: destFile="${file//\\/\/}". And $(dirname "$destFile") could be replaced by ${destFile%/*}. Guarding the mkdir invocation with a condition [ -d "${destFile%/*}" ] || mkdir ... can also save a bunch of slow, expensive fork+exec calls. – David Foerster Oct 13 '16 at 9:16
  • 1
    I would however suggest mv -pv "$file" "$destFile" instead of cp -pv "$file" "$destFile" – Ashwin Kumar k Oct 13 '16 at 9:20
  • @DavidFoerster. Thank you for the suggestions to improve the code. I have edited the code to include the suggestions. – Nizar Malangadan Oct 13 '16 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.