Replace string with lines stored in a file

OS version: RHEL 6.7
Shell : Bash

I have a file like below

$ cat pattern.txt
'T_PKT_HEADER'
'T_ORD_ITM_LOYX'
'T_ORDERITM_TRMS'
'T_ORDER_ITEM'
'T_ORDER_ITM_PRI'
'T_ORDER_ITEM_OM'
'T_ORDER_ITEM_XA'
'T_ORDER_ATT'
'T_ORDER_ACTNSET'
'T_ORDER_XM'
'T_ORDER_X'
'T_ORDER_TNTX'
'T_ORDER_POSTN'
'T_ORDER_DTL'
'T_ORDER'
'T_ORDER_BU'
.
.

For the below command I want to replace <tableName in Single Quotes> with each line from the above file.
Is there any way I could do this ? Expected output shown below

exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => <tableName in Single Quotes> ,degree => 3, cascade => true );

Expected output:

exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => 'T_PKT_HEADER' ,degree => 3, cascade => true );
exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => 'T_ORD_ITM_LOYX' ,degree => 3, cascade => true );
exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => 'T_ORDERITM_TRMS' ,degree => 3, cascade => true );
.
.
.
while read tableName
do
   echo "exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => <tableName in Single Quotes> ,degree => 3, cascade => true );" | sed 's/<tableName in Single Quotes>/'"$tableName"'/'
done < pattern.txt
1 Like

Why sed?

while read tableName
do
   echo "exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => '$tableName', degree => 3, cascade => true );"
done < pattern.txt
1 Like

Why shell? Try

sed "s/^/exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => /; s/$/ ,degree => 3, cascade => true );/" pattern.txt
1 Like

Thank You Rudic.

what does the sed clause /; s/$/ do ?

In fact, there's two s ubstitute operations, the ; separates the two. One ( s/^/.../ )substitutes the begin-of-line, the other ( s/$/.../ ) the end-of-line.

1 Like

Wouldn't

sed "s/\(^.*\)$/exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => \1 ,degree => 3, cascade => true );/" pattern.txt

have done it with one substitution?

Andrew
PS Where's the AWK solution? There has to be an AWK solution! :wink:

1 Like

@apmcd47: Here you go with an awk solution :cool:

Hello kraljic,

Could you please try following and let me know if this helps you.

awk -v s1="exec dbms_stats.gather_table_stats(ownname => 'SIEBEL',  tabname =>"  -v s2=",degree => 3, cascade => true );"  '{print s1,$0,s2}'   Input_file
 

Explanation: create s1 variable with value exec dbms_stats.gather_table_stats(ownname => 'SIEBEL', tabname => , create 2nd variable named s2 with value ,degree => 3, cascade => true ); and then simply print value of s1 then $0 (current line) and value of s2 .

Thanks,
R. Singh