Reputation: 485
So I'm pretty lost as I missed a week and am playing catch up, but I'm to write an awk program to tell the difference, in days, between two dates.
I'm more or less done with it, however it doesn't like it if the user inputs 01/01/YYYY when doing my data validation. I pull the 3 fields out of the arg then pass them to a function to validate.
the part that's giving me trouble is, in my validation:
if ( day > Days[month] ){
invalid stuff here
}
where Days[]
is an array holding [1]=31, [2]=28 (or 29 if leap) etc.
It hits true because Days[01] is not defined. I could go around it by defining a [01] as the same as [1] I suppose but I'd rather something more elegant.
How can I strip the leading zeros, within the awk program, of the variable month? Everything I've found is for use in a shell script and invokes awk, but that doesn't really help me.
Thanks for the help!
Upvotes: 4
Views: 12606
Reputation: 1517
Latest contribution somewhat shortened.
echo '20/02/1965' | awk '{sub ("/0", "/", $0)}1'
20/2/1965
Upvotes: 0
Reputation: 325
I tried the answer suggested by @paxdiablo. It ended up stripping the non-leading zeros as well.
$ echo '20/02/1965' | awk '{gsub ("^0*", "", $0); gsub ("/0*", "/", $0); print}'
2/2/1965
Using sub
instead gsub
worked fine for me.
$ echo '20/02/1965' | awk '{sub ("^0*", "", $0); sub ("/0*", "/", $0); print}'
20/2/1965
Upvotes: 2
Reputation: 5693
I'm sorry. My answer is not about awk, and it is about bash itself. So please don't give a minus for my comment)
echo -e "00000000" | sed -r 's/^[0]*$/0/g' | sed -r 's/^0[0]+//g'
Or perform integer calculations with (( )) notations
echo $((0000))
Upvotes: -2
Reputation: 882786
You need this, assuming your variable is called month
:
gsub ("^0*", "", month);
The ^
is the start anchor and 0*
means zero or more 0
characters. So this effectively removes all 0
characters at the start of the variable.
By way of example (which also shows a way to do it to the middle number as well, before splitting the date apart, see the second gsub
for that):
pax> echo '1/1/2013
03/12/2014
02/02/1965' | awk '{gsub ("^0*", "", $0); gsub ("/0*", "/", $0); print}'
1/1/2013
3/12/2014
2/2/1965
Upvotes: 6