Hi !
I'm trying to find the substring in a shell script as given:

#! /bin/bash
HTML="<html><body>OK</body></html>"
OK="OK"
OFFSET=`expr index $HTML $OK`
OK_LEN=`expr length $OK`

var1=`expr "$OFFSET"`
echo $var1
var2=`expr "$OK_LEN"`
echo $var2
INPUT=`echo | awk '{ print substr("'"$HTML"'",var2,var1) }'`

echo $INPUT

But on running it does not give me the output. The output I expect is "OK".
If I hardcode values of var1 and var2 ie if I write the expression as

INPUT=`echo | awk '{ print substr("'"$HTML"'",13,2) }'`

I'm getting the result as "OK".
Can you please suggest how can I use the variables instead of hard coding the parameters.

Recommended Answers

All 3 Replies

Ah!!

Got it!
I need to use quotes " ' " $var1" ' " with my variables

INPUT=`echo | awk '{ print substr("'"$HTML"'","'"$var1"'","'"$var2"'") }'`

Or just:

$ awk '{print substr($0,index($0,v),length(v))}' v="$OK"<<<$HTML
OK

or

$ awk '{match($0,v);print substr($0,RSTART,RLENGTH)}' v="$OK"<<<$HTML
OK
# echo $HTML | sed 's/<html><body>\(.*\)<\/body><\/html>/\1/'
OK
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.