I have a fair few files that have been extracted from a zip created in a strange way.

the files have come out of the tar.gz in windows file structure format

Example:

jpg_250\MI\00\00\00\19\MI0000001900.jpg

versus

jpg_250/MI/00/00/00/19/MI0000001900.jpg

The former is seen as a single file by linux.

I've been playing around with awk and sed to delimit the filename by backslash, and create the directories in question in the correct structure, and finally rename the file to the MI**.jpg and move it into the correct newly created end directory.

Is awk and sed the way to go here? I have awk exploding the filename into the 'directories' I need but I'm having trouble getting the directories actually created. I assume I would need sed at the end to rename the file into the MI**.jpg format.

Many thanks for any help.

share|improve this question
up vote 0 down vote accepted

You could do this with Perl like this.

# assume that the script was called like this:
# myscript file1 file2 etc...
# then all the files are in @ARGV

foreach $orig (@ARGV) {
    $orig_fixed = $orig;

    # convert the \ to /
    $orig_fixed =~ s!\\!/!g;

    #split the filename into directory and filename 
    ($dir, $filename) = ($orig_fixed =~ m!^(.*)/([^/]*)$!);

    # create the directory if it doesn't exist
    if (!-e $dir) {
        `mkdir -p $dir`; # -p means create the full path
    }

    # now move the file
    `mv '$orig' $dir/$filename`;

}
share|improve this answer
    
This creates the directory structure correctly but does not split the file into the MI***.jpg format and so does not move it at the end. The script seems to remove the slashes from the whole filename. mv: cannot stat `jpg_250MI00000011MI0000001100.jpg': No such file or directory – Alan Ogden Jan 6 '11 at 17:09
    
sorted. Just had to put the final $orig in single quotes. Many thanks! – Alan Ogden Jan 6 '11 at 17:27
    
don't need to shell out for mv, use Perl's rename. – glenn jackman Jan 6 '11 at 18:01
    
@glenn: I forget... does rename also move between directories? – Nathan Fellman Jan 6 '11 at 20:07
    
@Alan: fixed the answer – Nathan Fellman Jan 6 '11 at 20:07

Something like this?

$ ls 
a\b\c
a\b\d

$ for i in *; do
    F=$(echo $i | sed 's,\\,/,g')
    D=$(dirname $F)
    echo mkdir -p ${D}
    echo cp "${i}" "${F}"
done

mkdir -p a/b
cp a\b\c a/b/c
mkdir -p a/b
cp a\b\d a/b/d
share|improve this answer
    
This won't work, because you actually have to copy a\b\d into a/b, not only d – Nathan Fellman Jan 6 '11 at 16:54
    
the cp line should use $i, not $F – Nathan Fellman Jan 6 '11 at 16:54
    
@Nathan Fellman: You're right of course. Fixed it. – chris Jan 6 '11 at 16:55
    
Now I can vote it up :-) – Nathan Fellman Jan 6 '11 at 17:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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