Rename files in multiple directories to the name of the directory Rename files in multiple directories to the name of the directory linux linux

Rename files in multiple directories to the name of the directory


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 \;


You can use rnm. The command would be:

rnm -fo -dp -1 -ns '/pd0/.txt' -ss '\.txt$' /path/to/the/directory

-fo implies file only mode.

-dp directory depth. -1 makes it recursive to all subdirectories.

-ns implies name string i.e the new name of the file.

/pd0/ is the immediate parent directory of the file which is subject to rename operation.

-ss is a search string (regex). '\.txt$' regex searches for file with .txt at the end of the filename.

/path/to/the/directory this is the path where the v_1, v_2 ... directories reside. You can pass the directories ( v_1, v_2 ...) too in place of the parent directory path. For example:

#from inside the parent directoryrnm -fo -dp -1  -ns '/pd0/.txt' -ss '\.txt$' v_* 


Seem pretty straightforward to me:

$ mkdir /tmp/sandbox$ cd /tmp/sandbox$ mkdir v_{1,2,3}$ touch v_{1,2,3}/file.txt$ rename -v 's#/file##' v_{1,2,3}/file.txtrename v_1/file.txt v_1.txtrename v_2/file.txt v_2.txtrename v_3/file.txt v_3.txt$ ls -Fv_1/  v_1.txt    v_2/  v_2.txt    v_3/  v_3.txt