0

I have below content in my parameter file.

[s_m_imgpstna]
$DBConnection1=Insight_QAT331_DB

[s_m_drcgctln]
$DBConnection1=Insight_QAT291_DB

[s_m_ioxgciln]
$DBConnection1=Insight_QAT291_DB

[s_m_reddecna]
$DBConnection1=Insight_QAT291_DB

[s_m_cd2gcpna]
$DBConnection1=Insight_QAT291_DB

[s_m_cd2gcpna]
$DBConnection1=Insight_QAT291_DB

[s_m_cd2gctna]
$DBConnection1=Insight_QAT291_DB

[s_m_g92gctsp]
$DBConnection1=Insight_QAT291_DB

[s_m_os2gcceu]
$DBConnection1=Insight_QAT291_DB

[s_m_ccpgctdf]
$DBConnection1=Insight_QAT291_DB

[s_m_ew4gciln]
$DBConnection1=Insight_QAT307_DB

[s_m_dr6gctln]
$DBConnection1=Insight_QAT291_DB

[s_m_dr2gctln] 
$DBConnection1=Insight_QAT291_DB

[s_m_dr4gctln]
$DBConnection1=Insight_QAT291_DB

Now I want to search for the pattern "cd2gcpna" which has two occurrence in file

[s_m_cd2gcpna]
$DBConnection1=Insight_QAT291_DB

[s_m_cd2gctna]
$DBConnection1=Insight_QAT291_DB

Now I want to replace string which is just below of that([s_m_cd2gctna]) row for all occurrences.

$DBConnection1=Insight_**QAT291**_DB

replace by

$DBConnection1=Insight_**QAT308**_DB
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
Amol Murkute
  • 45
  • 2
  • 7

2 Answers2

0

awk solution:

$ awk '/cd2gcpna/{p=1;print;next} \
   p{sub(/291/,"308");p=0}1' file

If you want to change your file inplace, with GNU awk you can do this:

awk -i inplace '/cd2gcpna/{p=1;print;next} \
   p{sub(/291/,"308");p=0}1' file

And with params:

$ awk -v pat="cd2gcpna" -v val1=291 -v val2=308 '$0~pat{p=1;print;next} \
    p{sub(val1,val2);p=0}1' file

From a shell script:

$ cat test.sh
#!/bin/bash

pat=$1
val1=$2
val2=$3
file=$4

awk -v pat="$1" -v val1=$2 -v val2=$3 '$0~pat{p=1;print;next} \
    p{sub(val1,val2);p=0}1' $file

And call it with:

$ ./test.sh cd2gcpna 291 308 file
Marc Lambrichs
  • 2,864
  • 2
  • 13
  • 14
0

sed method:

sed -i '/cd2gcpna/{n;s/QAT291/QAT308/}' file

To wrap that in a function, (easier to test than a script, the code's virtually the same either way):

# usage: rep_after flagstring fromstring tostring file
rep_after() { sed -i '/'"$1"'/{n;s/'"$2"'/'"$3"'/}' "$4" ; }

And call it like so:

rep_after  cd2gcpna  QAT291 QAT308  file
agc
  • 7,973
  • 2
  • 29
  • 50