D
D
Dmitry Usachyov2018-08-29 19:10:54
bash
Dmitry Usachyov, 2018-08-29 19:10:54

How to convert formatted time to milliseconds?

The essence of the problem:
It is necessary to write a bash script that would translate the formatted date into milliseconds.
The input line is the following:
1 d 11 h 12 m 23 s
In principle, I found how to translate, but there is a difficulty with parsing the string.
I think that the algorithm is as follows:
1) remove spaces between 1 and d, 11 and h, etc. so that the output is 1d 11h 12m 23s
2) split the string into words and shove it into different variables or into an array
3) convert each component to milliseconds
4) add everything up and be happy)
Now I have problems with the 1st point and the 2nd.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Drill, 2018-08-30
@SJay

It is possible like this:

#!/bin/bash

###
# ./str2msec.sh "1 d 11 h 12 m 23 s"
# 
# или так
# 
# echo "1 d 11 h 12 m 23 s" | xargs -0 ./str2msec.sh
###

argument="$1"
# Варианты аргументов:
#argument="1 d 11 h 12 m 23 s"
# or
#argument="1 d   12 m 23 s"
# or
#argument=" 11 h 23 s"
# or
#argument="11   hm 23"


## Убираем пробелы

data=${argument// /}
# Результат из примеров выше:
#data="1d11h12m23s"
# or
#data="1d12m23s"
# or
#data="11h23s"
# or
#data="11hm23"
echo
echo "data = $data"
echo

## Регуляркой делим на элементы
re='([0-9]+[d])?([0-9]+[h])?([0-9]+[m])?([0-9]+[s])?'

## Ищем совпадения и вычисляем
if ; then
    echo "BASH_REMATCH  = ${BASH_REMATCH}"
    echo "BASH_REMATCH1 = ${BASH_REMATCH[1]}"
    echo "BASH_REMATCH2 = ${BASH_REMATCH[2]}"
    echo "BASH_REMATCH3 = ${BASH_REMATCH[3]}"
    echo "BASH_REMATCH4 = ${BASH_REMATCH[4]}"

    days=$(( $((${BASH_REMATCH[1]%d})) * 24 * 60 * 60 * 1000 ))
    hours=$(( $((${BASH_REMATCH[2]%h})) * 60 * 60 * 1000 ))
    minutes=$(( $((${BASH_REMATCH[3]%m})) * 60 * 1000 ))
    seconds=$(( $((${BASH_REMATCH[4]%s})) * 1000 ))
    result=$(( ${days} + ${hours} + ${minutes} + ${seconds} ))
else
    echo "not matched"
    exit 1
fi

echo
echo "Result = $result msec"
echo

D
Denis, 2018-08-29
@notwrite

Is it the script on the bash? maybe date is enough?

A
Aleksandr, 2018-08-29
@alexgearbox

1) You need to remove all spaces: 1d11h12m23s
2) (\d+[d|h|m|s])Divide the resulting “word” into elements by the expression. (For example, in a text editor, print each part of the "word" on a new line: \1\n)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question