Bash Script to Convert Milliseconds to Days:Hours:Minutes:Seconds:Milliseconds
awk, bash
Solution
Split into millisecond and second, using GNU date, you should be easier to get the result
#!/bin/bash
INPUT="$1"
while read t rest
do
ms=$(echo $t|sed -r "s/.*(.....)$/\1/") # get Milliseconds 617mS
se=$(echo $t|sed -r "s/(.....)$//") # get seconds 1882224
days=$(echo $se / 3600 / 24 |bc)
d="$days:$(date -d "1970-01-01 $se seconds" +%H:%M:%S):$ms"
echo "$d $rest"
done < $INPUT
Problem
I wrote the following bash script to convert milliseconds to Days:Hours:Minutes:Seconds:Milliseconds to make a log file more readable: ``` #!/bin/bash ### Constants ### CON_DAYS=.0000000115741 CON_HOURS=.000000277778 CON_MINUTES=.000066667 CON_SECONDS=.001 ### Variables ### INPUT="$1" cat $INPUT | awk -v CON_HOURS=$CON_HOURS -v CON_MINUTES=$CON_MINUTES -v CON_SECONDS=$CON_SECONDS -v CON_DAYS=$CON_DAYS ' { $1=substr($0,0,10) } { MILLISECONDS = $1 } { DAYS = int(MILLISECONDS * CON_DAYS) } { MILLISECONDS = MILLISECONDS - int( DAYS / CON_DAYS ) } { HOURS = int(MILLISECONDS * CON_HOURS) } { MILLISECONDS = MILLISECONDS - int(HOURS / CON_HOURS) } { MINUTES = int(MILLISECONDS * CON_MINUTES) } { MILLISECONDS = MILLISECONDS - int(MINUTES / CON_MINUTES) } { SECONDS = int(MILLISECONDS * CON_SECONDS) } { MILLISECONDS = MILLISECONDS - int( SECONDS / CON_SECONDS ) } { $1 = DAYS":"HOURS":"MINUTES":"SECONDS":"MILLISECONDS"ms" } {print}' exit ``` Section of Input File: ``` 1882224617mS ATMChannel: [1] CMLinkLayer Rx: 'DialDigits' (ls) 1882224617mS ATMIO: [1] TONE DIAL (11 digits) 1882224617mS ATMChannel: [1] StateChange Connected->ToneDialing ``` There are several lines of output that shows that it is not working correctly: ``` 22:19:224:14:186ms ATMChannel: [1] CMLinkLayer Rx: 'DialDigits' (ls) 22:19:224:14:186ms ATMIO: [1] TONE DIAL (11 digits) 22:19:224:14:186ms ATMChannel: [1] StateChange Connected->ToneDialing ``` After several hours of troubleshooting I am unable to find my error. Any help would be much appreciated.