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

标签 linux shell text sed substitution

我有一个文件包含:

asd x    
sometihng else    
asd x    
sometihng else    
asd x

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

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

谢谢,亚历克斯

最佳答案

使用 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}'

关于linux - 用数组中的值替换多行字符串的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514653/

相关文章:

linux - asm little-endian 寄存器/立即数/内存顺序

linux - 交互式 Shell 脚本

Linux:将字数 append 到文件的每一行

javascript - 在 CSS 形状内包装文本

linux - 如何从另一个文件中读取文件

c - 如何将程序输出重定向到文本文件

linux - 如何自动更新AWS ec2实例配置文件

linux - 在shell脚本中最后一次出现单词之前获取子字符串

php - Jquery显示来自mysql的文本

python - 文本文件之间的交集