用数组中的值替换许多线上的字符串末端



我有一个包含:

的文件
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

使用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]).*/12/;x;s/^[0-9] //;x}'

最新更新