Search code examples
bashmacosrename

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

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