循环目录和文件的好方法

时间:2013-10-28 11:48:18

标签: bash loops find directory

我正在尝试遍历一组文件夹,并且如果一个(或多个)文件中的文件比特定日期更新,它应该显示该文件夹及其中的文件,某些内容像这样;

(日期是一周)

Folder 1
  file 1
*Folder 2 (no files matching the date, should not be visible/echo'ed)*
Folder 3
  file 1
  file 2
Folder 4
  file 1

如何实现这一目标?我的示例代码是:

#!/opt/bin/bash
#
# CurrentTvList.sh
# File for generating a current list of stored tvshows on my nas
# Patrick Osterlund
# 

#set -x
#trap read debug

# Settings
#
NEWTMPFOLDER="/volume1/tmp/tvtemps/"
NEWTMPFILE="TmpTvlisting.txt"
SIMPLER=$NEWTMPFOLDER$NEWTMPFILE
SMALL=2
MEDIUM=14
LARGE=30

# Clear screen; remove later
clear

#check if dir exists
mkdir -p ${NEWTMPFOLDER}

#check if file exists
if [ -f $SIMPLER ];
then
   echo "File: $NEWTMPFILE exists in $NEWTMPFOLDER" $'\n'

   FILEDATE=$(date -r $SIMPLER)
    #Check if file is newer than the existing one
    if [[ $SIMPLER -nt $FILEDATE ]]; then
        echo "$SIMPLER is newer than $FILEDATE"
    else
        echo "file created $FILEDATE is newer than file created; $SIMPLER"
    fi
   echo "and it was created: $FILEDATE" #$'\n\n'
   echo "File was created: " > $SIMPLER 
   echo $FILEDATE >> $SIMPLER $'\n'
else
   echo "File $NEWTMPFILE does not exists in $NEWTMPFOLDER, creating it"
   touch $SIMPLER;
fi
# Mostly for checking if all went well:
echo "looking here:" $NEWTMPFOLDER;
echo "file: $NEWTMPFILE"

# Small list
echo "New shows last ${SMALL} days: " $'\n' >> $SIMPLER
find /volume2/Disk2/!Tv-Serier/ -type f -mtime -$SMALL -size +2048 -exec basename {} \; | sed 's/\.[^.]*$//'\
>> $SIMPLER

# Medium list
echo $'\n' "New shows last ${MEDIUM} days: " $'\n' >> $SIMPLER
find /volume2/Disk2/!Tv-Serier/ -type f -mtime -$MEDIUM -size +2048\
 -exec basename {} \; | sed 's/\.[^.]*$//' >> $SIMPLER | sort -df

# Not in use right now
# Large list
#echo $'\n' "New shows last ${LARGE} days: " $'\n' >> $SIMPLER
#find /volume2/Disk2/!Tv-Serier/ -type f -mtime -$LARGE -size +2048\
# -exec basename {} \; | sed 's/\.[^.]*$//' >> $SIMPLER | sort -df

1 个答案:

答案 0 :(得分:0)

您可以-newerct选项find列出当前目录中上周修改过的文件,如下所示:

find . -maxdepth 1 -type f -newerct '1 week ago'

此处-maxdepth 1将搜索范围限制在当前目录中; -type f仅选择普通文件(不是子目录等),-newerct c表示“inode更改时间”,t表示“将下一个参数解释为直接cvs

理解的表格的日期说明

所以你的脚本看起来像这样:

something | while read DIRECTORY; do {
    cd -- "$DIRECTORY"
    if find . -maxdepth 1 -type f -newerct '1 week ago' | grep -q .
    then
        printf "%s\n" "$DIRECTORY"
        printf "  %s\n" *
    fi
} done

其中something是列出要搜索的目录的命令。

我在上面的代码中假设您的意思是您在问题中写的内容:也就是说,如果目录中的任何文件比一周前更新,那么您要列出所有目录中的文件。