地带awk程序前导零 [英] strip leading zeros in awk program
问题描述
所以我pretty丢失我错过了一个星期,我打赶上,但我写一个awk程序分辨出来,以天,两个日期之间。
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.
我或多或少用它做,但是如果用户输入当仁不让的数据验证时,01/01 / YYYY它不喜欢它。我拉了3场出arg的然后将它们传递给一个函数来验证。
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
}
其中,天[]
是一个数组控股[1] = 31,[2] = 28(或29,如果飞跃)等。
where Days[]
is an array holding [1]=31, [2]=28 (or 29 if leap) etc.
由于天[01]没有定义它击中如此。我可以去解决它通过定义[01]因为同为[1]我想,但我宁愿东西更优雅。
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.
我怎样才能剥去前导零,awk程序中,变量一个月?我发现一切都在一个shell脚本使用和awk调用,但这并不能真正帮助我。
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.
感谢您的帮助!
推荐答案
您需要这个,假设你的变量称为月
:
You need this, assuming your variable is called month
:
gsub ("^0*", "", month);
的 ^
是启动锚和 0 *
表示零个或多个 0
字符。因此,这有效地在变量的开始删除所有 0
字符。
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.
通过举例的方式(这也说明了一个办法把它做对的中的数量为好,除了拆分日之前,看到第二个 GSUB
为):
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
这篇关于地带awk程序前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!