2

I have files as follows: (Some files are located inside nested folders)

/1/asd.m
/3/asd.m
/4/2/asd.m

I want to rename .m files with a suffix of their parent folder name. The result should be like this:

/1/asd1.m
/3/asd3.m
/4/2/asd2.m

How can I do this on Mac terminal?

Elander
  • 63
  • 6

2 Answers2

2

Simplier and more universal way that takes dirnames with spaces into consideration:

find . -name '*.mp3' -exec bash -xc 'dn=$(dirname "{}"); fn=$(basename "{}"); mv -v "{}" "$dn/$dn-$fn" ' \;

Result (verbosity via bash -x):

++ dirname './80 дней вокруг света/56.mp3'
+ dn='./80 дней вокруг света'
++ basename './80 дней вокруг света/56.mp3'
+ fn=56.mp3
+ mv -v './80 дней вокруг света/56.mp3' './80 дней вокруг света/./80 дней вокруг света-56.mp3'
./80 дней вокруг света/56.mp3 -> ./80 дней вокруг света/./80 дней вокруг света-56.mp3
Kirill Kay
  • 787
  • 1
  • 7
  • 16
0

If the name of the folder that contains your files is rename_folder:

rename_folder/1/asd.m
rename_folder/3/asd.m
rename_folder/4/2/asd.m

You can rename those files with this command:

find rename_folder -type f -name "*.m" -exec sh -c 'x="{}"; fn="${x##*/}"; dn="$(dirname $x)"; mv "$x" "${dn}/${fn%%.*}${dn##*/}.${fn#*.}"' \;

Results should be:

rename_folder/1/asd1.m
rename_folder/3/asd3.m
rename_folder/4/2/asd2.m
Hamid Rouhani
  • 2,309
  • 2
  • 31
  • 45
  • I used your code but had a problem when there is a space in the path or file name. dirname was not working properly. I just added a "'s in (dirname "$x") I used the following modified code: find rename_folder -type f -name "*.m" -exec sh -c 'x="{}"; fn="${x##*/}"; dn="$(dirname "$x")"; mv "$x" "${dn}/${fn%%.*}${dn##*/}.${fn#*.}"' \; – Hussam Kazah Sep 03 '19 at 08:17