Unix时间戳记和file.zip

时间:2019-02-10 02:24:31

标签: bash shell

在bash中,我想提取一部分文件名并添加该文件示例的unixtimestamps:

我的文件名为 auto0-20190210-013032-1726436102-de_mirage-servername.dem

我想将其压缩成这样的名称: dem-de_mirage-1549758632-1549759944.zip

其中:

de_mirage是我要从名称中提取的那部分,因为它在某些文件中会发生变化

1549758632是创建文件时的Unix时间戳

1549759944是上次修改文件时的Unix时间戳

我拥有用于​​压缩文件的功能:

for file in `find "$DIR" -mmin +1 -name '*.dem' -print` do zip -j $file.zip $file echo " `basename $file`" mv -ft "$OUT" "$file".zip done

1 个答案:

答案 0 :(得分:1)

这是您代码的修订版。

在注释中添加了提取文件名特殊部分和查找mtime / ctime的替代方法。

for file in `find "$DIR" -mmin +1 -name '*.dem' -print`
    do
        ## strip prefix - simple bash version may be too general
#       special=${file#*-*-*-*-}

        ## strip prefix - complicated but bad match is less likely
        special=$(echo "$file"|grep -Po '^.+?-\d{8}-\d{6}-\d+-\K.+(?=\.dem$)')

        ## remove trailing servername (assuming it doesn't contain hyphens)
#       special=${special%-*}

        ## remove trailing servername (assuming it is a fixed string)
        ## can be repeated to remove multiple different server names
        special=${special%-servername1}
        special=${special%-servername2}

        ## see "perldoc -f stat" for possible stat fields that can be used
        ## this example outputs 9:mtime and 10:ctime
#       mctime=$(perl -e 'printf "%d-%d",(stat $ARGV[0])[9,10]' "$file")

        ## see "man stat" for other timestamp options
        ## creation time (birthtime %W) may not be supported
        ## this example outputs mtime-ctime
        mctime=$(stat --printf='%Y-%Z' "$file")

        zipfile="dem-${special}-${mctime}.zip"

        zip -j "$zipfile" "$file"
        echo "  $(basename "$file")"
        mv -ft "$OUT" "$zipfile" 
    done