我有一个问题,如何将时间从 12 小时 AM/PM 格式转换为 24 小时?例如,我有来自标准输入的输入,一些文本如下:
The event starts at 03:25PM and is expected to end at 06:17PM.
Registration will be opened from 09:00AM until 06:00 PM.
The event starts at 15:25 and is expected to end at 18:17.
Registration will be opened from 09:00 until 06:00 PM.
如何读取所有 hh:mmPM 和 hh:mmAM 并将其转换?但我不想使用 awk 或类似的东西。我怎样才能只使用 bash 循环、if/else、echo、sed 等来做到这一点?谢谢!
答案1
生成替换数字的 sed 脚本:
#! /bin/bash
for pm in {0..11} ; do
(( h = pm + 12 ))
pm=$(printf %02d $pm)
echo "s/$pm\(:[0-9][0-9]\) \?PM/$h\1/g"
done | sed -e 's/ \?AM//g' -f- input.txt
该循环生成以下脚本:
s/00\(:[0-9][0-9]\) \?PM/12\1/g
s/01\(:[0-9][0-9]\) \?PM/13\1/g
s/02\(:[0-9][0-9]\) \?PM/14\1/g
s/03\(:[0-9][0-9]\) \?PM/15\1/g
s/04\(:[0-9][0-9]\) \?PM/16\1/g
s/05\(:[0-9][0-9]\) \?PM/17\1/g
s/06\(:[0-9][0-9]\) \?PM/18\1/g
s/07\(:[0-9][0-9]\) \?PM/19\1/g
s/08\(:[0-9][0-9]\) \?PM/20\1/g
s/09\(:[0-9][0-9]\) \?PM/21\1/g
s/10\(:[0-9][0-9]\) \?PM/22\1/g
s/11\(:[0-9][0-9]\) \?PM/23\1/g
多余的表达式会被删除AM
,同时保持时间不变。