用新值bash替换矩阵的某些元素

时间:2016-05-10 15:09:27

标签: arrays bash file matrix sed

我正在尝试读取文件,更改它的某些部分并将其写入bash中的新文件。我知道我可以用" sed"命令,但我不知道如何在我的情况下,这是我的文件开头的矩阵。这是我的文件的样子

alpha
1  0  0
0  1  0
0  0  1 
some text here
more numbers here

我试图在像

这样的for循环中替换上面矩阵的值
for i in 1 2 3 4 
do
replace 1 0 0
        0 1 0   
        0 0 1
 by     1*(1+${i})  ${i}/2  0
        ${i}/2         1    0
        0              0    1
and print the whole file with the substitution to newfile.${i}
done

我想在bash中这样做。知道怎么做吗?而且我只想改变这一部分而只是改变这一部分!

1 个答案:

答案 0 :(得分:0)

Awk更适合这个:

for i in {1..4}; do awk -v i="$i" -f substitute.awk oldfile.txt > newfile.$i; done

使用以下substitute.awk脚本:

{
 if( NR == 3 ) { print 1 + i, i / 2, 0 }
 else if( NR == 4 ) { print i / 2, 1, 0 }
 else print $0
}

(假设,正如你所写,矩阵总是在第3到第5行;在你的例子中,它在第2到4行)

相关问题