Linux 将多个目录下的文件重命名为目录名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14306117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:39:07  来源:igfitidea点击:

Rename files in multiple directories to the name of the directory

linuxrenamebatch-rename

提问by giskou

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 renamebut I can't figure out how to use it with folder and file renaming at the same time.

我想我可以使用,rename但我不知道如何同时使用文件夹和文件重命名。

采纳答案by Csq

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

结果可以通过 bash for 循环和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 \;

回答by tchrist

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.txt
rename v_1/file.txt v_1.txt
rename v_2/file.txt v_2.txt
rename v_3/file.txt v_3.txt

$ ls -F
v_1/  v_1.txt    v_2/  v_2.txt    v_3/  v_3.txt

回答by Jahid

You can use rnm. The command would be:

您可以使用rnm。命令将是:

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

-foimplies file only mode.

-fo暗示仅文件模式。

-dpdirectory depth. -1 makes it recursive to all subdirectories.

-dp目录深度。-1 使其递归到所有子目录。

-nsimplies name string i.e the new name of the file.

-ns暗示名称字符串,即文件的新名称。

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

/pd0/是要进行重命名操作的文件的直接父目录。

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

-ss是一个搜索字符串(正则表达式)。'\.txt$'正则表达式搜索文件 .txt名末尾的文件。

/path/to/the/directorythis 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:

/path/to/the/directory这是 v_1, v_2 ... 目录所在的路径。您也可以传递目录 ( v_1, v_2 ...) 代替父目录路径。例如:

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