目录中的最新文件

时间:2013-12-03 16:12:02

标签: bash directory

您好我有两个目录

目录1:

song.mp3
work.txt

目录2:

song.mp3
work.txt

这些文件是相同的,但directory1中的song.mp3比directory2中的song.mp3更新,而目录2中的work.txt最新是目录1中的work.txt。

现在我可以打印两个文件,例如 在目录2中较新的file1文件中,因此它必须是song.mp3 并且在目录1中较新的file2文件中,因此它必须是work.txt

我试过

find $directory1 -type f -newer $directory2

但它总是打印出两个目录中的最新文件。有人能帮助我吗?

3 个答案:

答案 0 :(得分:0)

-newer $directory2只是使用目录$directory2上的时间戳作为所有比较的参考点。它不会查看$directory2内的任何文件。

我认为在find中内置的操作并不像“将每个文件与其他目录中的对应文件进行比较”,因此您可能需要自己完成一些工作。这是一个简短的脚本,演示了一种可行的方法:

(cd $directory1 && find . -print) | while IFS= read -r fn; do
  if [ "$directory1/$fn" -nt "$directory2/$fn" ]; then
    printf "%s\n" "$directory1/$fn"
  else
    printf "%s\n" "$directory2/$fn"
  fi
done

答案 1 :(得分:0)

如果您使用的Linux支持以下内容:

Fileage=`date +%s -r filename`

您可以运行“查找”并以秒为单位打印年龄,然后是每个文件的文件名,然后对该文件进行排序。这样做的好处是它可以在任意数量的目录中运行 - 而不仅仅是两个。 Glenn更广泛使用的“stat -c”可用来代替我的“日期”命令 - 他为你做了“排序”和“awk”!

答案 2 :(得分:0)

# set up the test
mkdir directory1 directory2
touch directory1/song.mp3
touch -t 200101010000 directory1/work.txt
touch -t 200101010000 directory2/work.txt
touch directory2/work.txt

# find the newest of each filename:
#  sort the files in both directories by mtime
#  then only output the filename (regardless of directory) the first time seen
stat -c '%Y %n' directory[12]/* | 
sort -rn | 
cut -d " " -f 2- | 
awk -F / '!seen[$2]++'
directory2/work.txt
directory1/song.mp3