problem with shell variables in awk
I have a command which is executed successfully on command line:
ls -l | awk '/Sep 26/{split($8,a,":");if(a[1]a[2]>=1045 && a[1]a[2]<=1145)print $9}'
I am including the same thing in a shell script below:
#!/bin/ksh
date1=$1
date2=$2
time1=$3
time2=$4
ls -l| awk -v d1=${date1} -v d2=${date2} -v t1=${time1} -v t2=${time2} '/d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 && a[1]a[2]<=t2) print $9}'
But this does not work.please see below the execution
ksh -vx test.sh Sep 26 1045 1145
#!/bin/ksh
date1=$1
+ date1=Sep
date2=$2
+ date2=26
time1=$3
+ time1=1045
time2=$4
+ time2=1145
ls -l| awk -v d1=${date1} -v d2=${date2} -v t1=${time1} -v t2=${time2} '/d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9}'
+ awk -v d1=Sep -v d2=26 -v t1=1045 -v t2=1145 /d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9}
+ ls -l
awk: syntax error near line 1
awk: bailing out near line 1
I am using Solaris OS:I have tried with nawk now but there is no error but also there is no output.
pearl[ncm_o11.2_int.@].293> ksh -vx test.sh Sep 26 1045 11开发者_运维百科45
#!/bin/ksh
date1=$1
+ date1=Sep
date2=$2
+ date2=26
time1=$3
+ time1=1045
time2=$4
+ time2=1145
ls -l| nawk -v d1=${date1} -v d2=${date2} -v t1=${time1} -v t2=${time2} '/d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9}'
+ ls -l
+ nawk -v d1=Sep -v d2=26 -v t1=1045 -v t2=1145 /d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9}
When i am executing with out the shell variables inside the script.its executing perfectly.
*Note:*I am using Solaris OS.
I figured out the problem lies in the final framed command inside shell script:
ls -l|nawk -v d1=Sep -v d2=26 -v t1=1045 -v t2=1145 '/d1 d2/{split($8,a,":");if(a[1]a[2] >=t1 && a[1]a[2]<=t2)print $9}'
But i am not sure why this is failing to give the correct output with -v flags
As already suggested, if you need a dynamic regular expression, you need to use $0 ~ d1 " " d2
instead of /d1 d2/
.
Which operating system? It's possible that when you run the command interactively awk points to a different awk implementation. If you're on Solaris, for example, try running your script with nawk (or gawk), instead of awk.
精彩评论