Link to home
Start Free TrialLog in
Avatar of scurtis_1
scurtis_1

asked on

SED: How to replace instances of String "{0}" with the value of a variable?

Hi,

Background:

In the following script, I call a SQL script which puts its resultset into a text file called quota_text.lis; which is referenced using the variable QUOTA_TEXT_LIS. I then take the first line of QUOTA_TEXT_LIS, remove any chunks of spaces using sed and tokenize it on a ':' delimter; placing each chunk of the line into a LINE_? variable.

COUNT=5

$ORACLE_HOME/bin/sqlplus $TELEAPPUSER/$TELEAPPPWD@$ORACLE_SID @$DBSCRIPTS/quota_text 1 "QUOTA"

TEXT_LINE=`head -n 1 $QUOTA_TEXT_LIS|sed -e 's/^[ \t]*//;s/[ \t]*$//' -e 's/ *: */:/g'`
echo "[$TEXT_LINE]"
LINE_1=`echo $TEXT_LINE | cut -f1 -d:`
LINE_2=`echo $TEXT_LINE | cut -f2 -d:`
echo "RXCOUNT is: $RXCOUNT"
LINE_3=`echo $TEXT_LINE | cut -f3 -d: | sed -e 's/{0}/$COUNT/g'`

The content of LINE_3 is:

"You have {0} unread messages"

and I want to replace the instance of {0} with the value of the COUNT variable using sed (or something else if there is a better solution???).

For some reason it currently results in LINE_3 looking like:

"You have $COUNT unread messages"

because the String "$COUNT" is replacing {0} rather the the value of the COUNT variable?

Question:

Can anyone tell me how to make it replace the {0} section with the actual assigned value of the COUNT variable, please?

Thanks
Scott
Avatar of stefan73
stefan73
Flag of Germany image

Hi scurtis_1,
You must leave the single quote mode to use shell variables:

LINE_3=`echo $TEXT_LINE | cut -f3 -d: | sed -e 's/{0}/'$COUNT'/g'`


Cheers,

Stefan
Avatar of scurtis_1
scurtis_1

ASKER

Stefan,

Thanks for the quick response. It seems to almost work; but now I get the following:

++ cut -f3 -d:
++ sed -e 's/{0}/' 0 /g
sed: -e expression #1, char 6: Unterminated `s' command

As you can see it has put the value of my variable into the sed command but now the sed command is failing?

Scott
scurtis_1,

This is a classic one for PERL:

(bash array syntax:)

LINES= ( $( perl -e '
$text_line = <>;
$text_line =~ s/^\s+|\s+$//g;
$text_line =~ s/\s*\:\s*/\:/g;

@fields=split(/\s*\:\s*/,$text_line);
$fields[2] =~ s/\{0\}/$ENV{COUNT}/g;
print "\"$fields[0]\" "\"$fields[3]\" "\"$fields[2]\"";
'  $QUOTA_TEXT_LIS ) )

(ksh array syntax:)

set -A LINES $( perl -e '
$text_line = <>;
$text_line =~ s/^\s+|\s+$//g;
$text_line =~ s/\s*\:\s*/\:/g;

@fields=split(/\s*\:\s*/,$text_line);
$fields[2] =~ s/\{0\}/$ENV{COUNT}/g;
print "\"$fields[0]\" "\"$fields[3]\" "\"$fields[2]\"";
'  $QUOTA_TEXT_LIS )

Now you have ${LINES[0]}, ${LINES[1]}, ${LINES[2]} set with the values you need.

ASKER CERTIFIED SOLUTION
Avatar of stefan73
stefan73
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent! That's got it!

Thanks

Scott