incrementing a number in bash with leading 0

2019-06-12 14:00发布

I am a very newbie to bash scripting and am trying to write some code to parse and manipulate a file that I am working on.

I need to increment and decrement the minute of a time for a bunch of different times in a file. My problem happens when the time is for example 2:04 or 14:00.

File Example:

2:43
2:05
15:00

My current excerpt from my bash script is like this

for x in `cat $1`;
  do minute_var=$(echo $x | cut -d: -f2);
  incr_min=$(($minute_var + 1 | bc));
  echo $incr_min;
done

Current Result:

44
6
1

Required Result:

44
06
01

Any suggestions

8条回答
一夜七次
2楼-- · 2019-06-12 14:53
while IFS=: read hour min; do 
    printf "%02d\n" $((10#$min + 1))
done <<END
2:43
2:05
15:00
8:08
0:59
END
44
06
01
09
60

For the minute wrapping to the next hour, use a language with time functions, like gawk

awk -F: '{
    time = mktime("1970 01 01 " $1 " " $2 " 00")
    time += 60
    print strftime("%M", time)
}' 
perl -MTime::Piece -MTime::Seconds -nle '
    $t = Time::Piece->strptime($_, "%H:%M");
    print +($t + ONE_MINUTE)->strftime("%M");
'
查看更多
疯言疯语
3楼-- · 2019-06-12 14:58

Padding with 0, and getting two last characters:

for x in `cat $1`;
  do minute_var=$(echo $x | cut -d: -f2);
  incr_min=0$(($minute_var + 1 | bc));
  echo ${incr_min: -2:2};
done
查看更多
登录 后发表回答