我在我的参数文件中有以下内容。
[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现在我想搜索在文件中出现两次的模式"cd2gcpna“
[s_m_cd2gcpna]
$DBConnection1=Insight_QAT291_DB
[s_m_cd2gctna]
$DBConnection1=Insight_QAT291_DB现在,我想为所有出现的字符串替换([s_m_cd2gctna])行下面的字符串。
$DBConnection1=Insight_**QAT291**_DB替换为
$DBConnection1=Insight_**QAT308**_DB发布于 2017-10-27 22:14:15
awk解决方案:
$ awk '/cd2gcpna/{p=1;print;next} \
p{sub(/291/,"308");p=0}1' file如果你想就地更改你的文件,使用GNU awk,你可以这样做:
awk -i inplace '/cd2gcpna/{p=1;print;next} \
p{sub(/291/,"308");p=0}1' file并使用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在shell脚本中:
$ 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并使用以下命令调用它:
$ ./test.sh cd2gcpna 291 308 file发布于 2017-10-30 00:42:25
sed方法:
sed -i '/cd2gcpna/{n;s/QAT291/QAT308/}' file为了将其封装在函数中(比脚本更容易测试,无论哪种方式,代码实际上都是相同的):
# usage: rep_after flagstring fromstring tostring file
rep_after() { sed -i '/'"$1"'/{n;s/'"$2"'/'"$3"'/}' "$4" ; }并这样称呼它:
rep_after cd2gcpna QAT291 QAT308 filehttps://stackoverflow.com/questions/46975410
复制相似问题