Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 ?

share|improve this question

4 Answers 4

With bash:

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

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?

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

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.

share|improve this answer

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 :-) .

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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