Linux bash脚本按列表复制文件

时间:2016-08-02 14:02:48

标签: bash

我是bash的新手,我需要帮助。我有一个文件调用list.txt包含像

这样的模式
1210
1415
1817

我想要做的是编写一个bash脚本,它将当前目录中包含该模式的所有文件复制到名为toto的新目录。

当前目录中我的文件示例:

1210_ammm.txt
1415_xdffmslk.txt
1817_lsmqlkksk.txt
201247_kksjdjdjd.txt 

目标是将1210_ammm.txt1415_xdffmslk.txt1817_lsmqlkksk.txt复制到toto

'answer'转移。

我的list.txt和toto目录位于我当前的目录中。这就是我尝试的方法

#!/bin/bash

while read p; do # read my list file 

  for i in `find -name $p -type f` # find all file match the pattern

   do

   cp $i toto # copy all files find into toto

   done

done < partB.txt

我没有错误,但它没有完成这项工作。

3 个答案:

答案 0 :(得分:2)

以下是您需要实施的内容:

read tokens from an input file
for each token
   search the files whose name contain said token
   for each file found
     copy it to toto

要从输入文件中读取令牌,您可以在while循环中使用read命令(通常为Bash FAQ,具体为Bash FAQ 24

要搜索名称中包含字符串的文件,可以使用for循环和globbing。例如,for file in ./*test*; do echo $file; done将打印当前目录中包含test的文件名。

要复制文件,请使用cp

您可以检查this ideone sample是否有效。

答案 1 :(得分:0)

使用以下脚本:

cp "$(ls | grep -f list.txt)" toto

ls | grep -f list.txt将对list.txt输出中ls中找到的模式进行grep。

cp将匹配的文件复制到toto目录。

注意:如果list.txttoto不在当前目录中,请在脚本中提供绝对路径。

答案 2 :(得分:0)

我也需要这个,我试过@Zaziln的答案,但它给了我错误。我刚刚找到了一个更好的答案。我认为其他人也会感兴趣。

mapfile -t files < test1.txt
cp -- "${files[@]}" Folder/

我在这篇文章中找到了它 - &gt; https://unix.stackexchange.com/questions/106219/copy-files-from-a-list-to-a-folder#106231