Dear All
The following is part of my script:
echo ${myarray[j]}
mytitle=`awk '{print substr(${myarray[j]}, 0, length(${myarray[j]})-4)}' /dev/null`
the echo ${myarray[j]} works fine;
however, I keep getting following error for the mytitle=.. part:
awk: line 1: syntax error at or near {
awk: line 1: syntax error at or near ,
awk: line 1: syntax error at or near )
awk: line 1: extra ')'
Can someone tell me what mistake did I make?
Yoda
2
You have to assign an external variable to awk
variable to start working on it.
No need to use /dev/null
, you can print inside BEGIN
block.
Also starting character in substr
function is character number 1
not 0
mytitle=$( awk -v ARR="${myarray[j]}" 'BEGIN { print substr(ARR,1,length(ARR)-4) }' )
1 Like
You cannot embed shell variables in an awk statement that way.
Generally
var=foo
awk -v myvar=$var '{.....}' somefile
-v [awkvariable name]=$variable
It looks like you are trying to get a substring of a variable. Some shells like bash provide that.
${string:position:length}
example:
a=123456789
len=${#a} # length of the variable
len=$(( $len -1 4 ))
echo ${a:0:len} # get string minus 4 characters
It is much less efficient in awk, but you can it this way (one of several) if you are not using the bash shell:
var=123456789
newvar=$(echo "$s" | awk '{print substr($0,1,length($0)-4) }')
1 Like
Thank you very much!
I followed your methods; and all of them work perfectly! Thank you so much!