I need to rename a couple of files using shell scripting, by a certain "key". This key includes both strings as well as extracted portions of file path that I get with find
.
I am on a Mac, OSX El Capitan and am using ZSH. Here is the directory tree:
├── 300x250
│ ├── 300x250-img-fallback.jpg
│ └── index/
├── 300x600
│ ├── 300x600-img-fallback.jpg
│ └── index/
├── 336x280
│ ├── 336x280-img-fallback.jpg
│ └── index/
└── 970x250
├── 970x250-img-fallback.jpg
└── index/
I need to rename ../index/ folders into ../c2_[parentFolderName]/. This is what I am trying:
find . -type d -mindepth 2 -maxdepth 2 -exec sh -c 'echo -- mv "$0" "$(dirname "$0")"/"C2_"$(basename "$0/..")""' {} \;
This doesn't seem to be the proper way to get the basename
of the parent unfortunately.
find . -name "*index" -exec sh -c 'echo -- mv "$0" "$(dirname "$0")"/"C2_"$(basename "$0/..")""' {} \;
This one is just a variation which also does not work (there is no reason why it should :) ).
I am quite new to shell scripting and am trying to learn as much as possible in a shell agnostic kind of way, so please disregard that I am using ZSH currently.
$0
is the programs/function name while$1
...,$n
are the positional parameters. I've added links to documentation. See also Is there a reason why the first element of a Zsh array is indexed by 1 instead of 0? – Stéphane Chazelas Aug 30 '16 at 11:42{}
with sayfind
, the results get automatically "ordered" into variables$0
,$1
,$2
, ... Seems that there is much more to learn. – Alexander Starbuck Aug 30 '16 at 13:56sh -c '...' a b c
, indeeda
goes to$0
andb
to$1
, but$0
is interpreted as the name of that inline script, not an argument to that inline script, just like when you runsh myscript a b c
,myscript
(this time not inline) getsa
,b
,c
as arguments ("$@"
) andmyscript
in$0
. So you should give the name that you want to give to that inline script as that first argument (I usually usesh
). Where it matters is that that$0
gets used in error messages. Try for instance:sh -c 'echo > /' foo bar
– Stéphane Chazelas Aug 30 '16 at 14:12sh -c 'echo > /' foo bar
, as you suggested, I got this:foo: /: Is a directory
:) – Alexander Starbuck Aug 30 '16 at 14:16foo
, as that's what ended up in$0
(the inline script name). – Stéphane Chazelas Aug 30 '16 at 14:18