如何在终端中查找并复制任意文件列表?

dav*_*_lr 5 command-line find copy

我现在正试图在终端中查找文件。我找到了很多关于如何查找特定模式的文件的答案,例如以特定扩展名或特定时间范围结尾的文件等。

不过,我一直试图弄清楚如何查找和复制多个任意文件,例如特定文件的列表。

举例来说,我有以下文件夹和文件

/Documents/Folder_1/内容:

file1.txt file2.txt file3.txt file4.txt
Run Code Online (Sandbox Code Playgroud)

/Documents/Folder_2/内容:

file5.txt file6.txt file7.txt
Run Code Online (Sandbox Code Playgroud)

/Documents/Folder_3/内容:

file8.txt, file9.txt
Run Code Online (Sandbox Code Playgroud)

我想做的是创建一个名为Folder_4并复制的新文件夹file2.txtfile5.txt然后file9.txt复制到该新文件夹。

有没有办法通过终端来做到这一点?

我尝试做的是制作文件名的文本列表并将其命名为 list.txt 之类的名称,例如

file2.txt
file5.txt
file9.txt
Run Code Online (Sandbox Code Playgroud)

并将该文本文件加载到“查找”命令中,例如如下所示:

find /home/usr/Documents -name $cat list.txt
Run Code Online (Sandbox Code Playgroud)

我认为我会将输出提供给文本列表或复制命令,但这似乎不起作用。

我想知道是否有任何方法可以通过 Find 命令查找多个任意文件,或者我是否以错误的方式思考这个问题?

编辑:只是想感谢您的回答并总结我最终解决这个问题的方式。我特别感谢有人向我解释 find 命令的设计目的不是接受多个没有 -o 标志的输入,这让我觉得不那么愚蠢了,因为无法弄清楚!

我最终做的是制作一个小 shell 脚本并要求用户输入并使用数组和 for 循环来迭代列表。

基本上我最终得到的脚本或多或少是这样的:

file1.txt file2.txt file3.txt file4.txt
Run Code Online (Sandbox Code Playgroud)

Sha*_*_m2 0

仍在尝试以最清晰的方式弄清楚你的问题。

您是否想在目录中查找某些特定文件?如果是,并且有一个模式,您可以使用正则表达式来查找它们,然后使用find <directory> -regex "your_regex" ,如果没有模式,您需要指定您要查找的文件名。您可以使用下面的 python 脚本来复制文件。

import shutil
import os

list = [file1.txt, file2.txt] # replace with your file list.
destination = "your_destination" # replace with your destination.
directory = os.getcwd() # replace os.getcwd() with your directory.

for dirpath, dirname, filenames in os.walk(directory, topdown='true'):
    for file in filenames :
        if file in list :
            shutil.copy(os.path.join(dirpath, file), destination) 
Run Code Online (Sandbox Code Playgroud)

如果以上不是你的情况,那么我建议使用这个:

find <somewhere> -name "something" | xargs cp -t <your_destination>
Run Code Online (Sandbox Code Playgroud)


Ser*_*nyy 0

下面的 bash 脚本,如果从顶级目录(比如您的~/Documents文件夹)执行,将创建新目录并复制/移动您想要的文件。默认情况下,它仅回显找到的文件,以便用户可以检查这是否是他们想要的结果。注意:替换echocp复制或mv 移动。

文件列表分配给regex带分隔符的变量\|(forgrep表示逻辑或语句)

copy_files.sh:

#!/bin/bash
new_dir="./dir4"
[ -d "$new_dir" ] ||  mkdir "$new_dir"
regex="file1\|file3\|file6"
find . -print0 | while IFS= read -d $'\0' line;
do
    if grep -q "$regex" <<< $line
    then
       filename=$(basename "$line")
       printf "%s\n" "Found $filename"
       echo "$line" "$new_dir"/"$filename"
       # Replace echo with cp for copying,
       # or mv for moving
    fi   
done
Run Code Online (Sandbox Code Playgroud)
bash-4.3$ ./copy_files.sh 
Found file6
./dir3/file6 ./dir4/file6
Found file3
./dir1/file3 ./dir4/file3
Found file1
./dir1/file1 ./dir4/file1
Run Code Online (Sandbox Code Playgroud)

正如您在上面看到的,该脚本报告找到了哪个文件以及它将复制或移动到哪里,例如在最后一行,./dir1/file1如果./dir4/file1实际上使用的是cpormv而不仅仅是echo