Issue
I have a bash script that reads in data from an RTC via i2cdump
#!/usr/bin/env bash
TIME=$(i2cdump -r 0-6 -y 0 0x68 b)
TIME=${TIME:76:20}
echo $TIME
OUTPUT: 16 44 17 03 15 11 22
The output is in the form SEC MIN HOUR DAY DATE MONTH YEAR
I would like to now set my system time based on this output using timedatectl
which requires the output be transformed
# timedatectl set-time 'YEAR-MONTH-DATE HOUR:MIN:SEC'
How can I transform a string of form SEC MIN HOUR DAY DATE MONTH YEAR
to 'YEAR-MONTH-DATE HOUR:MIN:SEC'
?
I've tried replacing the spaces with colons for the time, but don't know how to properly format the date to be preceding the time.
Solution
Probably just passing the old format to read and then assemble from the variables is the cleanest way:
TIME="16 44 17 03 15 11 22"
read SEC MIN HOUR DAY DATE MONTH YEAR <<< "$TIME"
NEWTIME="20$YEAR-$MONTH-$DAY $HOUR:$MIN:$SEC"
echo "$NEWTIME"
or more old fashion with piping into a while loop:
echo $TIME | while read SEC MIN HOUR DAY DATE MONTH YEAR; do
NEWTIME="20$YEAR-$MONTH-$DATE $HOUR:$MIN:$SEC"
echo "$NEWTIME"
done
Output:
2022-11-15 17:44:16
Of course sed
and awk
also works, though slightly less readable:
echo "16 44 17 03 15 11 22" | sed -e's/\([0-9][0-9]\) \([0-9][0-9]\) \([0-9][0-9]\) \([0-9][0-9]\) \([0-9][0-9]\) \([0-9][0-9]\) \([0-9][0-9]\)/20\7-\6-\5 \3:\2:\1/'
2022-11-15 17:44:16
echo "16 44 17 03 15 11 22" | awk '{print 20$7"-"$6"-"$5" "$3":"$2":"$1}'
2022-11-15 17:44:16
Answered By - treuss Answer Checked By - Willingham (WPSolving Volunteer)