Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename files in multiple directories to the name of the directory

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.

like image 567
giskou Avatar asked Jan 13 '13 17:01

giskou


People also ask

Is there a way to rename multiple files at once with different names?

Select multiple files in a folder. To do so, press and hold down the CTRL key while you are clicking files. After you select the files, press F2. Type the new name, and then press ENTER.

How do I rename multiple folders at once?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do I rename multiple files in a directory in Linux?

How do you rename multiple folders in Linux? The mv command ( mv source target ) renames the file/folder named by the source operand to the destination path named by the target operand. However, the mv works with a single file name and directory/folder name on Linux and Unix-like system.


2 Answers

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 \;
like image 114
Csq Avatar answered Sep 30 '22 17:09

Csq


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 directory
rnm -fo -dp -1  -ns '/pd0/.txt' -ss '\.txt$' v_* 
like image 41
Jahid Avatar answered Sep 30 '22 18:09

Jahid