【问题标题】:Copy or move files to another directory based on partial names in a text file根据文本文件中的部分名称将文件复制或移动到另一个目录
【发布时间】:2018-05-07 19:49:31
【问题描述】:

我想根据文本文件中的部分文件名将一些文件从目录A 复制到目录B

我尝试了下面的命令,但它不起作用

for fn in $(cat filename.txt); do find . -type -f -name '$fn*' \
    -exec rsync -aR '{}' /tmp/test2 \;

文件名的格式为abcd-1234-opi.txtrety-4567-yuui.txt。我必须从文件名中提取数字,然后将这些文件复制到另一个文件夹,我在文本文件中有数字。

有人可以指导我吗?

【问题讨论】:

  • 我很难看到一个模式。你能举一个更好的例子吗?文件名结构要准确。
  • 文件名格式为 abcd-1234-opi.txt, rety-4567-yuui.txt ,我必须从文件名中提取数字,然后将这些文件复制到另一个文件夹,我有数字一个文本文件

标签: linux bash shell command-line scripting


【解决方案1】:

应该避免重复运行find。相反,以编程方式将表达式分解到find 命令行中。

awk 'BEGIN { printf "find . -type -f \\("; sep="" }
   { printf "%s -name \047*%s*\047", sep, $0; sep=" -o" }
   END { printf " \\) -exec rsync -aR '{}' /tmp/test2 \\;\n" }' filename.txt |
sh

将管道留给sh进行测试。

【讨论】:

    【解决方案2】:

    如果理解正确,搜索的模式是第一个-之后的前3位数字,如下所示:

    abd-12312-xyz
        ^^^
    
    88-45644-oio
       ^^^
    
    qwe-78908-678
        ^^^
    

    这是一种写法:

    while read line; do
        pattern=${line#*-}
        pattern=${pattern:0:3}
        find . -type f -name "*$pattern*" -exec rsync -aR {} /tmp/test2 \;
    done < patterns.txt
    

    如果您的输入类似于“veeram_20171004-104805_APOLLO_9004060859-all.txt”, 你想提取“9004060859”, 然后你可以尝试找到不同的逻辑来提取它。 例如, “切断最后一个'-'之后的所有内容,以及最后一个'_'之前的所有内容”。 你可以这样写:

    pattern=${line%-*}
    pattern=${pattern##*_}
    

    【讨论】:

    • Janos,我的文件名中有 9 位数字,例如 veeram_20171004-104805_APOLLO_9004060859-all.txt 我必须将包含 9004060859 的文件名复制到另一个文件夹,我有数字文本文件
    • @VijayMuddu 这与您的问题完全不同。那么模式是什么?最后一个数字序列?
    • 是的,上面示例文件名中包含 9004060859 的最后一个数字序列,我在文本文件中有数字
    • @ Janos 我试过但我得到了这个错误,>while read line;做 > 模式=${line%-} > 模式=${pattern##_} > 找到 . -type -f -name "$pattern" -exec rsync -aR {} /tmp/test2 \; > done
    • @VijayMuddu 我现在看到你在find 命令的参数中还有一个错误:它应该是-type f 而不是-type -f。所以从f 前面删除-。我相应地更新了我的答案。
    【解决方案3】:

    如果我理解你的问题是正确的:

    for file in $(<./example); do cp "${file}" /tmp/test2/; done
    
    for file in $(<./example); do find . -type f -name ${file} -exec rsync -aR {} /tmp/test2/ \; ; done
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2017-12-11
      • 2021-01-04
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多