0

I have a bunch of directories with different names within the current directory:

Hello World/
Dr. Dre - Still Dre/
Angry Birds/
2018 Grand Prix Race Highlights/

And within each of those directories are files (one in each, respectively):

source.c
song.aac
setup.apk
spanish.mp4

And I want to rename each file to their directory name but the extension shouldn't change. Sample output files:

Hello World.c
Dr. Dre - Still Dre.aac
Angry Birds.apk
2018 Grand Prix Race Highlights.mp4

Output location does not matter.

I've found so many solutions for renaming files within the current dir that use for file in * and mv "$file" "${file/oldname/newname}" but my files are in subdirectories 1 level deep so what I currently have is:

currdir=$(pwd)
for dir in */
do
  cd ${dir}
  file=$(echo *)
  ext=${file##*.}
  mv "*" "${dir}.${ext}"
  cd ${currdir}
done

I'm using zsh and when I try to run this function I get zsh: source.c not found which I suspect might be something wrong with the line file=$(echo *). I also don't like the complication of what I did there so maybe there's a cleaner way of doing it or even a one-liner. I only want to use commands which are already installed by default in Ubuntu such as mv, find, sed, vim, grep, etc. The directory names might have symbol characters like $, &, ., etc. so please accommodate weird names also.

0
4

I'd just do:

autoload zmv
zmv '(*)/(*)(.*)' '$1$3'

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.