Skip to content

Instantly share code, notes, and snippets.

@NickCis
Last active April 17, 2022 21:25
Show Gist options
  • Save NickCis/8a1261a0d9528771e70f935d6ee76b2c to your computer and use it in GitHub Desktop.
Save NickCis/8a1261a0d9528771e70f935d6ee76b2c to your computer and use it in GitHub Desktop.
#! /usr/bin/bash
## This script replaces time entries in am/pm format to 24hs
## $ echo "The event starts at 03:25pm and 11:11AM" | ./ampm-to-24
## The event starts at 15:25 and 11:11
# Match time entries: 03:25pm 11:11AM
regex='(0[0-9]|1[0-2]):([0-5][0-9])(AM|PM|am|pm)'
# Read STDIN line by line
while read line; do
# Search of all the occurences of the reges
while [[ $line =~ $regex ]]; do
hour=${BASH_REMATCH[1]}
min=${BASH_REMATCH[2]}
ampm=${BASH_REMATCH[3]}
# If its pm, sum 12
if [[ "${ampm^^}" = "PM" ]]; then
if [[ "$hour" != "12" ]]; then
hour=$(expr $hour + 12)
fi
elif [[ "$hour" = "12" ]]; then
hour="00"
fi
# Replace the hour
line=${line/"${BASH_REMATCH[0]}"/"$hour:$min"}
done
# Print line
echo $line
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment