正则表达式在 bash 中查找和复制(保留文件夹结构)?

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

Regex find and copy in bash (preserving folder structure)?

bashfind

提问by Jonathan Sternberg

I have a folder with a bunch of log files. Each set of log files is in a folder detailing the time and date that the program was run. Inside these log folders, I've got some video files that I want to extract. All I want is the video files, nothing else. I tried using this command to only copy the video files, but it didn't work because a directory didn't exist.

我有一个文件夹,里面有一堆日志文件。每组日志文件都在一个文件夹中,详细说明了程序运行的时间和日期。在这些日志文件夹中,我有一些要提取的视频文件。我想要的只是视频文件,没有别的。我尝试使用此命令仅复制视频文件,但它不起作用,因为目录不存在。

.rmv is the file extension of the files I want.

.rmv 是我想要的文件的文件扩展名。

$ find . -regex ".*\.rmv" -type f -exec cp '{}' /copy/to/here/'{}'

If I have a folder structure such as:

如果我有一个文件夹结构,例如:

|--root  
   |  
   |--folder1  
   |  |  
   |  |--file.rmv  
   |  
   |--folder2  
      |  
      |--file2.rmv  

How can I get it to copy to copy/to/here with it copying the structure of folder1 and folder2 in the destination directory?

我怎样才能让它复制到复制/到/这里,并在目标目录中复制folder1和folder2的结构?

采纳答案by Paused until further notice.

I would just use rsync.

我只会使用rsync

回答by K7g

cp has argument --parents so the shortest way to do what you want is:

cp 有参数 --parents 所以做你想做的最短方法是:

find root -name '*.rmv' -type f -exec cp --parents "{}" /copy/to/here \;

回答by martin clayton

The {}represents the full path of the found file, so your cpcommand evaluate to this sort of thing:

{}让你的代表找到的文件的完整路径,cp命令评估为这样的事情:

cp /root/folder1/file.rmv /copy/to/here/root/folder1/file.rmv

If you just drop the second {}it will instead be

如果你只是放弃第二个{},而是

cp /root/folder1/file.rmv /copy/to/here

the copy-file-to-directory form of cp, which should do the trick.

cp 的复制文件到目录形式,应该可以解决问题。

Also, instead of -regex, yor could just use the -nameoperand:

此外,您-regex可以只使用-name操作数,而不是:

find root -name '*.rmv' -type f -exec cp {} /copy/to/here \;

回答by martin clayton

Assuming srcis your rootand dstis your /copy/to/here

假设src是你的rootdst是你的/copy/to/here

#!/bin/sh

find . -name *.rmv | while read f
do
       path=$(dirname "$f" | sed -re 's/src(\/)?/dst/')
       echo "$f -> $path"
       mkdir -p "$path"
       cp "$f" "$path"
done

putting this in cp.shand running ./cp.shfrom the directory over root

将其放入cp.sh./cp.sh从根目录运行

Output:

输出:

./src/folder1/file.rmv -> ./dst/folder1
./src/My File.rmv -> ./dst
./src/folder2/file2.rmv -> ./dst/folder2

EDIT: improved script version (thanks for the comment)

编辑:改进的脚本版本(感谢您的评论)