Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MacOS/Bash – Replace filename with parent directory name

I have about 600 folders with one file each. The structure is as follow:

Folder: 123 Title of a file

File: Title of a file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So the filename and folder name are identical except for the number. I would like to add the number to the filename or just replace the whole filename with the folder name. I have put the following together, but I do not find a way to add the file extension.

for file in */*.txt; do echo mv -- "$file" "${file%/*}/${file%/*}"; done

I added it at the end "file/*.txt", but somehow it does not work.

Would appreciate some guidance – thanks!

>Solution :

The directory name doesn’t have the .txt extension name. You need to add that back when renaming the file.

for file in */*.txt; do 
    dir="${file%/*}"
    echo mv -- "$file" "$dir/$dir.txt"
done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading