递归地将特定类型的所有文件移动到 Bash 中的目标目录中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14345714/
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-09-09 23:11:59  来源:igfitidea点击:

Recursively moving all files of a specific type into a target directory in Bash

bashrecursionmv

提问by Mehran

How could I move all .txt files from a folder and all included folders into a target directory .

我怎样才能将文件夹中的所有 .txt 文件和所有包含的文件夹移动到目标目录中。

And preferably rename them to the folder they where included in, although thats not that important. I'm not exactly familiar with bash.

最好将它们重命名为包含它们的文件夹,尽管那不是那么重要。我对 bash 不是很熟悉。

回答by John Kugelman

To recursively move files, combine findwith mv.

要递归移动文件,请findmv.

find src/dir/ -name '*.txt' -exec mv {} target/dir/ \;

To rename the files when you move them it's trickier. One way is to have a loop that passes each file name through tr / _, which converts slashes into underscores.

在移动文件时重命名文件比较棘手。一种方法是让循环通过 传递每个文件名tr / _,将斜杠转换为下划线。

find src/dir/ -name '*.txt' | while read file; do
    mv "$file" "target/dir/$(tr / _ <<< "$file")"
done

回答by Mithrandir

Try this:

尝试这个:

find source -name '*.txt' | xargs -I files mv files target

This will work faster than any option with -exec, since it will not invoke a singe mv process for every file which needs to be moved.

这将比使用 -exec 的任何选项工作得更快,因为它不会为每个需要移动的文件调用单个 mv 进程。

回答by DigitalRoss

If it's just one level:

如果只是一层:

mv *.txt */*.txt target/directory/somewhere/.