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
Here's a solution that
is this ok for your requirement?
UPDATED #2
There are some problems with your script. At first instead of
`cat file`
you should use`<file`
or rather$(<file)
. Onefork
andexec
call is spared asbash
simply opens the file. On the other hand callingcut
andbc
(andprintf
) also not needed asbash
has internally the proper features. So you can spare somefork
s andexec
s again.If the input file is large (greater then cca 32 KiB) then the
for
-loop line can be too large to be processed bybash
so I suggest to usewhile
-loop instead and read the file line-by-line.I could suggest something like this in pure
bash
(applied Atle's substr solution):Input file
Output:
Maybe the
printf -v
is the simplest as it puts the result to the variable in a single step.Good question from
tripleee
what should happen if the result is 60.Try this:
Use
printf
to reformat the output to be zero-padded, 2-wide:Use
printf
:No that
bc
is not needed if only integers are involved.