I have a file containing lines of data that are amounts padded with leading zeros, similar to the snip below.
Using a shell script, how can I add up a column of numbers contained in lines when BASH interprets the numbers as octal when I do in-line math?
What an interesting puzzle you present to me! My first thought was that there’s a cool way I can solve this using a shell function, one that stripped a single leading zero then compared its results to the pre-truncated version of the value, until they matched (e.g., all the leading zeroes were deleted).
It’d look something like this:
while [ "$newvalue" != "$lastvalue" ]
newvalue="$(echo $myvalue | sed 's/^0//')"
# return value is the global variable 'newvalue'
This would then be called as stripzeroes “0000000003434″ (or whatever value you’d read in from the data file) and the result would be returned as the value newvalue without the leading zeroes.
Nice solution, classic little shell script function, but there’s one problem.
With the right regular expression, you can strip all the leading zeroes from your data fields with just a few characters:
valueWithoutZeroes="$(echo $valueWithZeroes | sed 's/0*//')"
That’s right, but using the proper regular expression to the sed command, you can very easily strip off all the leading zeroes, making your math far, far simpler and all without complicating your shell script with useless functions!
Hope that helps you out.