Steve
Steve

Reputation: 14912

ZSH: rename files in nested folders, capitalize specific letters

I have many nested folders of json language files, such as

da-dk.json
de-de.json
en-us.json

I need to change them all to capitalize the letters after the hyphen, as in

da-DK.json
de-DE.json
en-US.json

I am on a Mac with zsh. I originally thought I could do it with a GUI utility I have used called A Better Finder Rename but it apparently does not offer case conversions on replace.

I know regex and figured it would be something like find ^([a-z]{2})-([a-z]{2}) and replace with $1-\U$2 but I'm not sure how to do this in the command line.

Upvotes: 2

Views: 1332

Answers (3)

Masoud Ghaderi
Masoud Ghaderi

Reputation: 497

Given that you are using ZSH shell, you can use the awesome zmv command

zmv '(**/)(*)-(*).json' '${1}${2}-$3:u.json'

You may need to autoload zmv before running the above command.

Short explanation:

  • (**/) takes care of nested folders which is mapped to ${1}
  • First (*) matches the part before hyphen and is mapped to ${2}
  • Second (*) matches the part after hyphen and is uppercased by :u before being mapped to ${3}.

There are some useful material in this SO question and its answers.

Upvotes: 5

Gilles Quénot
Gilles Quénot

Reputation: 185053

In traditional shell commands:

for i in *.json; do
    echo mv "$i" "${i:0:3}$(tr '[[:lower:]]' '[[:upper:]]' <<< ${i:3:2}).json"
done

Drop echo when the output looks good.

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185053

With perl rename:

install via homebrew (if not already installed):

brew install rename

command:

rename -n 's/\w{2}(?=\.)/uc $&/e' *.json

Drop -n switch when the output looks good.

Upvotes: 0

Related Questions