Reputation: 105
I am trying to write an Awk program that takes two dates separated by / so 3/22/2013 for example and breaks them into the three separate numbers so that I could work with the 3 the 22 and the 2013 separately.
I would like the program to be called like
awk -f program_file 2/23/2013 4/15/2013
so far I have:
BEGIN {
d1 = ARGV[1]
d2 = ARGV[2]
}
This will accept both dates, but I am not sure how to break them up. Additionally, the above program must be called with nawk, with awk says it cannot open 2/23/2013.
Thanks in advance.
Upvotes: 1
Views: 169
Reputation: 204259
If you're on a machine with nawk and awk, there's a chance you're on Solaris and using /bin/awk or /usr/bin/awk, both of which are old, broken awk which must never be used. Use /usr/xpg4/bin/awk on Solaris instead.
Anyway, to your question:
$ cat program_file
BEGIN {
d1 = ARGV[1]
d2 = ARGV[2]
split(d1,array,/\//)
print array[1]
print array[2]
print array[3]
exit
}
$ awk -f program_file 2/23/2013 4/15/2013
2
23
2013
There may be better approaches though. Post some more info about what you're trying to do if you'd like help.
Upvotes: 0
Reputation: 195209
you cannot do it in your way. since awk thinks you have two files as input. that is, your date strings were looked as filenames. That's why you got that error message.
if the two dates are stored in shell variables, you could:
awk -vd1="$d1" -vd2="$d2" BEGIN{split(d1,one,"/");split(d2,two,"/");...}{...}'
the ...
part is your logic, in the line above, the splitted parts are stored in array one
and two
. for example, you just want to print the elements of one
:
kent$ d1=2/23/2013
kent$ d2=4/15/2013
kent$ awk -vd1="$d1" -vd2="$d2" 'BEGIN{split(d1,one,"/");split(d2,two,"/"); for(x in one)print one[x]}'
2
23
2013
or as other suggested, you could use FS
of awk, but you have to do in this way:
kent$ echo $d1|awk -F/ '{print $1,$2,$3}'
2 23 2013
if you pass the two vars in one short, the -F/
won't work, unless they(the two dates) are in different lines
hope it helps
Upvotes: 2
Reputation: 1
You could decide to use /
as a field separator, and pass -F /
to GNU awk
(or to nawk
)
Upvotes: 0
Reputation: 17467
How about it?
[root@01 opt]# echo 2/23/2013 | awk -F[/] '{print $1}'
2
[root@01 opt]# echo 2/23/2013 | awk -F[/] '{print $2}'
23
[root@01 opt]# echo 2/23/2013 | awk -F[/] '{print $3}'
2013
Upvotes: 0