2

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

eg:

C\Users\Welcome\Desktop\Doc1.docx
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

2
  • 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 . Oct 13, 2016 at 7:59
  • Ok, I believe you :) Oct 13, 2016 at 8:01

1 Answer 1

3

Use the following bash script.

#!/bin/bash
for file in *\\*
do 
    destFile="${file//\\/\/}"
    destFolder="${destFile%/*}"
    [ -d "$destFolder" ] || mkdir -p "$destFolder"
    mv -v "$file" "$destFile"
done

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
3
  • 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. Oct 13, 2016 at 9:16
  • 1
    I would however suggest mv -pv "$file" "$destFile" instead of cp -pv "$file" "$destFile" Oct 13, 2016 at 9:20
  • @DavidFoerster. Thank you for the suggestions to improve the code. I have edited the code to include the suggestions. Oct 13, 2016 at 9:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .