本文介绍了使用UNIX shell脚本的字符串替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的字符串替换以下列方式:

The output must be changed in line with the values from the reference file.

Input:

aaaa
val1=xxx
val2=yyy
val3=zzz
bbbb
val1=ppp
val2=qqq
val3=rrr
aaaa
val1=xxx
val2=yyy
val3=zzz

Reference File:

block   variable    value
aaaa    val1        iii
aaaa    val2        jjj
aaaa    val3        kkk
bbbb    val1        eee
bbbb    val2        fff
bbbb    val3        ggg

Output:

aaaa
val1=iii
val2=jjj
val3=kkk

bbbb
val1=eee
val2=fff
val3=ggg

aaaa
val1=iii
val2=jjj
val3=kkk

Currently I tried to do this using Sed command. Using which I was able to replace 1 block of code, ie,

aaaa
val1=xxx
val2=yyy
val3=zzz

into,

aaaa
val1=iii
val2=jjj
val3=kkk

The val1,val2,val3 variables occur in both the blocks 'aaaa' and 'bbbb'. But for block 'aaaa' the values will be different and for block 'bbbb' the values will be different.currently using 'sed' command I am able to replace the values for block 'aaaa', but for 'bbbb' block also the same values are being taken.

How to do a 'sed' command(or any other string replacement command) for a particular set of lines alone? My reqirement is, the control must check for the block names and then fetch the relavant values for the variables from the reference file.

It would be of great help if someone can give me a solution.

解决方案

Your question ought to be edited. I am ignoring all of it except "How to do a 'sed' command(or any other string replacement command) for a particular set of lines alone?" which seems to be the heart of the question.

sed accepts addresses. To specify specific lines by line number:

sed -e '4,6s/foo/bar/'

will replace the first instance of 'foo' with 'bar', but only on line 4 to 6.

sed -e '/baz/s/foo/bar/'

will do the replacement only on lines that match the pattern 'baz'.

sed -e '/baz/{/qux/s/foo/bar/; }'

will do the replacement only on lines that match the pattern 'baz' and the pattern 'qux'.

There are many ways to specify the lines on which you wish to execute a sed command. Reading the documentation may help. (ie man sed). In other words, RTFM.

这篇关于使用UNIX shell脚本的字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 18:55