ZIome3eg
ZIome3eg

Reputation: 15

Unix time stamps and part of filename in file.zip

In bash I would like to extract part of filename and add unixtimestamps of that file example:

I've got file named auto0-20190210-013032-1726436102-de_mirage-servername.dem

And I want to zip it to make name like this: dem-de_mirage-1549758632-1549759944.zip

where:

de_mirage is that part that I want to extract from name because it changes in some files

1549758632 is unix timestamp when the file was created

1549759944 is unix timestamp when the file was last time modifed

I've got that function for zipping files:

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

Upvotes: 1

Views: 283

Answers (1)

jhnc
jhnc

Reputation: 16797

Here's amended version of your code.

Alternative ways to pull out the special part of the filename and to find the mtime/ctime are added in comments.

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

Upvotes: 2

Related Questions