【问题标题】:Bash script to compare/search two directories using file list as variable使用文件列表作为变量比较/搜索两个目录的 Bash 脚本
【发布时间】:2013-05-09 08:11:19
【问题描述】:

我正在尝试编写一个 bash 脚本,该脚本将允许我获取 Dir1 上的文件名,并在 find 命令中使用每个文件名作为我的搜索字符串,然后在 Dir2 上运行 find 命令。然后,将搜索结果输出到文本文件。

因此,例如,当它运行时:

获取 Dir1 中的文件:

  • file1.txt
  • file2.txt
  • file3.txt
  • file4.txt

在 Dir2 中查找名称为“file1”的所有文件

file1 作为“file1-extrafile.txt”存在于 Dir2 中

将结果写入文本文件

使用“file2”作为搜索字符串重复。

我该怎么做? diff 会帮助我吗? for 循环?

【问题讨论】:

  • 这是未经测试的,但请尝试for FILE in `find '/path/to/dir1'`; do find '/path/to/dir2' -name '*$FILE*' >> /path/to/result.txt; done
  • 你关心 Dir1 和 Dir2 的子目录吗?您想要包含还是忽略子目录?
  • 您希望如何处理不同的扩展?你只关心 .txt 文件吗?或者你想忽略任何扩展?
  • 你的代码是什么样的?
  • @EmilSit 子目录也必须搜索

标签: bash unix


【解决方案1】:

试试这个:

for f in /dir1/*; do
  n=$(basename "$f")
  ls -1 /dir2/*${n%.*}*.${n##*.}
done > result.txt

【讨论】:

    【解决方案2】:
    find Dir1 -type f -printf '%f\0' | xargs -0 -n1 find Dir2 -name
    

    给定文件:

    Dir1/a/b/c
    Dir1/a/d
    Dir1/e
    
    Dir2/a/b
    Dir2/a/e
    Dir2/d
    Dir2/c
    Dir2/e/f
    

    将打印:

    Dir2/c
    Dir2/d
    Dir2/a/e
    Dir2/e
    

    【讨论】:

    • 您可以改用-print0
    • -print0 将等价于 -printf '%p\0',这是行不通的
    【解决方案3】:

    把它放在一个文件中(比如search.sh)并用./search.sh dir1 dir2执行它

    #!/bin/sh
    
    dir1=$1
    dir2=$2
    [ -z "$dir1" -o -z "$dir2" ] && echo "$0 dir1 dir2" 1>&2 && exit 1
    
    #
    # Stash contents of dir2 for easy searching later
    #
    dir2cache=/tmp/dir2.$$
    # Clean up after ourselves
    trap "rm -f $dir2cache" 0 1 2 15
    # Populate the cache
    find $dir2 -type f > $dir2cache
    
    #
    # Iterate over patterns and search against cache
    #
    for f in $(find $dir1 -type f); do
        # Extract base name without extension
        n=$(basename $f .txt)
        # Search for files that begin with base name in the cache
        fgrep "/$n" $dir2cache
    done
    

    【讨论】:

      猜你喜欢
      • 2011-05-09
      • 2022-10-18
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多