Rename files in multiple directories to the name of the directory

giskou picture giskou · Jan 13, 2013 · Viewed 26.1k times · Source

I have something like this:

v_1/file.txt
v_2/file.txt
v_3/file.txt
...

and I want to rename those files to something like this:

v_1.txt
v_2.txt
v_3.txt
...

in the same directory.

I guess I can use rename but I can't figure out how to use it with folder and file renaming at the same time.

Answer

Csq picture Csq · Jan 13, 2013

The result can be achieved with a bash for loop and mv:

for subdir in *; do mv $subdir/file.txt $subdir.txt; done;

Note that the solution above will not work if the directory name contains spaces. Related link.

Another solution based on comments (that works for directories having spaces in the name as well):

find . -type d -not -empty -exec echo mv \{\}/file.txt \{\}.txt \;