【问题标题】:Copy files (from list) from any subdirectory从任何子目录复制文件(从列表中)
【发布时间】:2015-10-07 17:59:15
【问题描述】:

我有一个包含如下文件列表的文本文件:

list.txt 的内容:

file1.txt
file2.txt
file3.txt

我需要搜索一个目录(及其子目录)以找到每个文件并将其复制到另一个目录中。

当前目录: -目录 -subdir1 -subdir2 -subdir3 -subdir4 -输出目录

在这个例子中,我可能会:

  • subdir3 中找到file1.txt
  • subdir1 中找到file2.txt
  • file3.txt 可能不存在

在这种情况下,它会将file1.txt & file2.txt 复制到outputdir

我没有太多经验会在命令行上执行此操作,但是要移动 1200 个文件,所以我无法手动执行此操作。这是我最接近正确的事情,但它没有找到任何文件,因为它们都在子目录中:

xargs -a list.txt cp -t outputdir

对您给出的命令的解释也将非常有帮助。周围的搜索也提出了“bash for loops”,我尝试使用但无法弄清楚所有复杂性:

FOR /R "%~dp0" %%I IN (.) DO  for /f "usebackq delims=" %%a in ("%~dp0list.txt") do echo d |xcopy "%%I\%%a" "outputdir" /e /i

【问题讨论】:

  • 部分问题是最后一位不是bash :)

标签: bash shell


【解决方案1】:

如果您有bash 4,请使用以下内容:

shopt -s globstar nullglob
while IFS= read -r fname; do
    files=("$dir"/**/"$fname")
    if (( ${#files[@]} > 0 )); then
        cp "${files[@]}" "$outputdir"
    fi
done < list.txt

while 循环一次从list.txt 读取一行。 ** 模式匹配零个或多个目录; files 可以包含 0 个或多个匹配文件。如果数组不为空,则将所有文件名传递给cp进行复制。

对于旧版本,请使用find

while IFS= read -r fname; do
    find "$dir" -name "$fname" -type f -exec cp {} "$outputdir" \;
done < list.txt

这只是定位$dir 下的所有匹配文件并在每个文件上运行cp

【讨论】:

  • 似乎可以工作,但我遇到了错误,可能需要调整代码。你能解释一下代码,以便我可以为我的真实东西进行故障排除吗?
猜你喜欢
  • 2016-07-08
  • 1970-01-01
  • 2020-02-15
  • 2014-04-03
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多