在目录中查找重复的文件名(不指定确切的文件名)

时间:2014-10-12 20:29:09

标签: linux bash shell unix

我有一个完整的文件目录,所有文件都遵循命名约定“file_001”“file_002”等。这些文件都存储在各个子目录中,有些文件具有相同的名称。

我使用了find命令并将输出重定向到一个文本文件,该文件包含目录中所有文件的路径列表,我正在尝试做的是在文本文件中搜索任何重复的文件名。

我对如何执行此操作的最佳猜测是使用grep,但我无法弄清楚正确的语法。

1 个答案:

答案 0 :(得分:3)

它只打印重复文件的名称:

find /your/path -type f -printf "%f\n" | sort | uniq -d

它打印重复文件的路径:

方法1:

find /your/path -type f | grep -F -f <(find /your/path -type f -printf "%f\n" | sort | uniq -d)

这是我最喜欢的,因为它不会保存磁盘中的任何临时文件。 它使用进程替换,因此请注意使用显式#!/bin/bash行调用脚本。您可以在此问题中查看详细信息:Syntax error in shell script with process substitution

方法2:

find /your/path -type f > your_file_with_paths.txt
find /your/path -type f -printf "%f\n" | sort | uniq -d |
while read FILENAME; do
    grep -F "$FILENAME" your_file_with_paths.txt
done

说明:

find /your/path -type f

此命令返回 / your / path 下的所有文件路径。


find /your/path -type f -printf "%f\n" | sort | uniq --repeated

只需要文件名而不是完整路径,对它们进行排序,然后只过滤重复的文件名(--repeated只是-d的长形式。)


grep -F -f <(find /your/path -type f -printf "%f\n" | sort | uniq --repeated)
# or
grep -F "$FILENAME" your_file_with_paths.txt

对于任何重复的文件名,请查找其路径。