This question arose from another question I had here ("How to extract basename of parent directory in shell"), which seems to have opened the "rabbit hole" down the Unix string manipulations for me. So, here goes supplementary question:
What is the correct way to extract various parts ("levels") from dirname
results combined with find
?
Let's assume I have the following hierarchy:
DE_AT/adventure/motovun/300x250/A2_300x250.zip
I "find" the file like so:
find . -name "*.zip"
execute shell on the find
results:
-exec sh -c '' {} \;
How would I extract each part of the full path? How do I get:
- DE_AT
- adventure
- motovun
- 300x250
- A2_300x250.zip
This is what I know so far:
basename "$1" # gets me: A2_300x250.zip
dirname "$1" # gets me: ./DE_AT/adventure/motovun/300x250
I am asking this because I need to rename this .zip files into someString_DE_AT_motovun+A2_300x250.zip.
I came up with a horrible frankensolution like so:
find . -name "*.zip" -exec sh -c '
mv "$0" "myString_$(basename $(dirname $(dirname \
$(dirname "$0")_...+$(basename "$0")"
' {} \;
I don't even wish to try this because this simply cannot be correct.
zsh
solution? I am trying to getman zmv
but I have no entries :(. What is the -n switch and why $1, $2, $3 when in first one you are using 2, 4 and 6? Sorry for being a total noob here :/ – Alexander Starbuck Aug 31 '16 at 11:51zsh
like for any biggish manual likebash
's, I'd useinfo
instead ofman
. If you doinfo zsh
, typei
to get the index, enterzmv
(completion abailable), it should take you to thezmv
documentation. – Stéphane Chazelas Aug 31 '16 at 12:09i
while ininfo zsh
I get the message: "No indices available". – Alexander Starbuck Aug 31 '16 at 12:20info zsh
only gives you a dump of the man page. If on a Debian-like system, you may need to install thezsh-doc
package. – Stéphane Chazelas Aug 31 '16 at 12:22zsh
solution works brilliantly :) but also moves the renamed .zip files to top of the hierarchy (to a containing folder banners/, which holds /DE_AT/, /DE_DE/ and /DE_CH/ folders; how can I not move them?) – Alexander Starbuck Aug 31 '16 at 12:30zmv '...' '${f:h}/someString...'
where$f
is the original file, and${f:h}
its head (dirname). (use${file%/*}
for the other solutions) – Stéphane Chazelas Aug 31 '16 at 12:39