I am struggling with a sed command. I am trying to achieve this:
Input: 03:23PM
Output: 15:23PM
My sed command which I have tried:
echo $line | sed 's/03:..PM/15:..PM/g
To remember part of the replacement test, use parentheses. To refer to the first pair of parentheses, use \1:
sed 's/03:\(..\)PM/15:\1PM/g'
In fact, you can make both the : and PM part of the capture group:
sed 's/03\(:..PM\)/15\1/g'
Using sed
$ sed '/[0-9:]*[AP]M/s/^[^:]*/15/' <<< $line
15:23PM
Or using @dawg solution to handle multiple ranges
sed "/PM/s/^[^:]*/echo \$((&+12))/e" <<< $line
15:23PM
I would use awk so you are getting actual addition and can detect AM vs PM:
echo '03:23PM
11:33PM
03:23AM' | awk 'BEGIN{FS=OFS=":"} /PM/ && $1<12 {$1=$1+12} 1'
Prints:
15:23PM
23:33PM
03:23AM