Will
Will

Reputation: 2410

Shell - Retrieve part of a filename using pattern

What is the best way to extract the time from this filename and converting it in seconds since 00:00 of current day (no timestamp) and using pure bash?

/a/very/long/path/to/my/files/2019-07-02_06_12_55_SOME_FOO_BAR.log

Output excpected :

extractTimeinSecond() {
 // code
}
filetime=$(extractTimeinSecond $file)
echo $filetime # 22375

I'd have done something like this, but this isn't very sexy as I'm sure there is a better way to get it.

extractTimeinSecond() {
   file=$1 # /a/very/long/path/to/my/files/2019-07-02_06_12_55_SOME_FOO_BAR.log
   shortfile=$(basename $file) # 2019-07-02_06_12_55_SOME_FOO_BAR.log
   time=$(echo $shortfile | cut -d '_' -f 2,3,4) # 06_12_55
   h=$(( $(echo $time | cut -d '_' -f1) * 60 * 60 )) # 06 * 60 * 60 = 21600
   m=$(( $(echo $time | cut -d '_' -f2) * 60 )) # 12 * 60 = 720
   s=$(echo $time | cut -d '_' -f3) # 55
   echo $(( $h + $m + $s )) # 21600 + 720 + 55 = 22375
}


Upvotes: 1

Views: 39

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15438

To cleanly collect time components: Assuming log=/a/very/long/path/to/my/files/2019-07-02_06_12_55_SOME_FOO_BAR.log,

$: f="${log##*/}"                       # strip path
$: IFS=_ read date h m s trash <<< "$f" # parse time elements
$: echo "$date $h:$m:$s"                # check values
2019-07-02 06:12:55

$: secstamp=$( date +%s -d "$date $h:$m:$s" )
echo $secstamp
1562065975

I assume you want the seconds into the day of the log's timestamp, even if checking on a different day?

$: midnight=$( date +%s -d "$date 00:00:00" )
$: echo $midnight
1562043600

Subtract for the seconds.

$: echo $(( secstamp - midnight ))
22375

An awk solution will be much faster, but this is a great trick to add to the toolbox.

Upvotes: 2

mouviciel
mouviciel

Reputation: 67929

Using awk:

extractTimeinSecond() {
   basename "$1" | awk -F'[-_]' '{print ($4*60+$5)*60+$6}'
}

Using bash only:

extractTimeinSecond() {
   a=${1##*/}
   b=${a#*_}
   hour=${b/_*}
   c=${b#*_}
   minute=${c/_*}
   d=${c#*_}
   second=${d/_*}
   echo $(((hour*60+minute)*60+second));
}    

Upvotes: 2

Related Questions