用数组中的值替换多行上的字符串结尾

时间:2017-04-20 08:51:10

标签: linux shell text sed substitution

我有一个包含以下内容的文件:

asd x    
sometihng else    
asd x    
sometihng else    
asd x

以及包含values=(3,4,5)的数组。 现在我想替换" x"在文件的第一行,使用shell脚本中向量中的第一个元素的值。适用于所有行/元素。这样我得到了

asd 3
sometihng else
asd 4
sometihng else
asd 5

我该怎么做?

截至目前,我尝试在循环中使用sed。像这样:

values=(3 4 5)
lines=3
for currentLine in $(seq $lines)
do
     currentElement=$(expr "$currentLine" / "2")
     sed "$currentLine s/\(asd\)\(.*\)/\1 ${values[$currentElement]}/"
done

但是对于每次循环运行,我得到了整个原始文件,其中编辑了有趣的行,如下所示:

asd 3
sometihng else    
asd x    
sometihng else    
asd x

asd x
sometihng else    
asd 4    
sometihng else    
asd x

asd x
sometihng else    
asd x    
sometihng else    
asd 5

谢谢,Alex

1 个答案:

答案 0 :(得分:0)

使用awk

会更容易
awk 'BEGIN { a[1]=3; a[2]=4; a[3]=5; } /x/ { count++; sub(/x/, a[count]); } { print }'

但是,如果你坚持sed,你可以尝试这样的事情:

{ echo "3 4 5"; cat some_file; } | \
    sed '1{h;d};/x/{G;s/x\(.*\)\n\([0-9]\).*/\1\2/;x;s/^[0-9] //;x}'