All, I have a string from which I want to extract a substring. The thing is that the starting position is stored in variable. AWK Doesn't seem to recognize the variable.

Here is the code

str="This is a test"  
s1="is"  
i=$(awk -v a="$str" -v b="$s1" 'BEGIN{print index(a,b)}')  
echo "$str" | awk '{print substr($0,$i)}'

But this doesn't work. How do coerce awk to recognize i ?

link|improve this question

71% accept rate
feedback

4 Answers

With bash:

awk -v value="$i" '{print substr($0,value)}' <<< "$str"
link|improve this answer
feedback

The variable is not being passed into awk. Instead of

echo "$str" | awk '{print substr($0,$i)}'

do

echo $str | awk -v i="$i" '{print substr($0,i)}'

However, the output is

% ./a.sh
is is a test

What is your intended output?

link|improve this answer
I want the output to be "is a test" – smokinguns Oct 13 '11 at 22:56
feedback

Why not do all the processing in a single invocation of awk?

haystack="This is a test"
needle="is"
printf '%s\n' "$haystack" | awk -v "needle=$needle" '{\
    i=index($0, needle)
    if (i) print substr($0, i)
}

If you need your shell script to also see the value of i, you could add > "/dev/tty" to the end of the print command above, then add another line saying merely print i with no redirect, then wrap the whole printf ... | awk ... line in a i=$(...) construct.

link|improve this answer
feedback

Direct answer to the original question: by escaping the quotation marks and letting the shell expand the variable:

awk '{print substr($0,'$i')}'

If it is suspected that the variable might contain blank space and other things and one wants it treated as a string in awk, one can just use even more quotation marks:

awk '{print index($0,"'"$s1"'")}'

...but one is often doing something less than optimal if it comes to this :-) .

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.