2

I have a folder containing many .zip files. They are named like this:

John-Rupert A. Doe_nnnnnnn_assignsubmission_file_*.zip

where n is a digit, * is a string and John-Rupert A. Doe is a string that may contain spaces, dots and dashes.

For each of them, I want to do the following:

  1. create a directory. I do this via:

    ls | cut -d'_' -f 1 | sed 's/ //g' | tr -d '.' | tr -d '-' | xargs -L 1 mkdir
    

    (So, the corresponding directory name for the example above would be JohnRupertADoe)

  2. Now I want to extract each .zip file into the directory created using this .zip file name. But how?

3

You could try with:

for z in ./*.zip
do name="${z%%_*}"; dest=".${name//[ .-]/}"; mkdir "$dest"; unzip "$z" -d "$dest"
done

For each zip file it extracts the name part ( ${z%%_*} deletes suffix greedily) it then removes any occurrence of dot, dash and space (${name//[ .-]/}) and passes the resulting string as an argument to mkdir to create the corresponding directory. It then unzips the archive to the specified destination.

0

Untested:

for i in *.zip; do
  zipdir() { echo "$i" | cut -d'_' -f 1 | sed 's/ //g' | tr -d '.' | tr -d '-'; }
  zipdir | xargs -L 1 mkdir
  mv "$i" "$(zipdir)"/
done

Or to remove both tr pipes, you could just add to your pipe to sed (also untested):

for i in *.zip; do
  zipdir() { echo "$i" | cut -d'_' -f 1 | sed 's/ //g;s/.//g;s/-//g'; }
  zipdir | xargs -L 1 mkdir
  mv "$i" "$(zipdir)"/
done
  • 1
    tr -d ' .-' works too, to delete spaces, dots and dashes. or sed 's/[- .]//g' – cas Nov 21 '15 at 22:47
  • I thought on many systems, tr -d could only take a single character as an argument...was I completely wrong in thinking this??? – rubynorails Nov 21 '15 at 23:35
  • 1
    not to my knowledge. afaik, tr always works on sets of characters. – cas Nov 21 '15 at 23:37
  • Very good to know. Thanks. Maybe I had it confused with the fact that I normally use it with single characters for replacement/substitution since results can get a little crazy if multiple characters are involved in that type of scenario. – rubynorails Nov 21 '15 at 23:37

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.