在awk中传递变量行号和字符串以在文件中打印

时间:2015-03-26 23:56:42

标签: awk zsh

将zsh中的变量行号和字符串传递给awk并让awk在给定行号处插入字符串的语法是什么样的?

#!/bin/zsh

freq_pols=('10 10' '10 11c' '10 11s' '10 20' '10 21c' '10 21s' '10 22c' '10 22s' '11c 11c' '11c 11s' '11c 20' '11c 21c' '11c 21s' '11c 22c' '11c 22s' '11s 11s' '11s 20' '11s 21c' '11s 21s' '11s 22c' '11s 22s' '20 20' '20 21c' '20 21s' '20 22c' '20 22s' '21c 21c' '21c 21s' '21c 22c' '21c 22s' '21s 21s' '21s 22c' '21s 22s' '22c 22c' '22c 22s' '22s 22s')

line_number_O=('8' '11' '14' '17' '20' '23' '26' '29' '32' '35' '38' '41' '44' '47' '50' '53' '56' '59' '62' '65' '68' '71' '74' '77' '80' '83' '86' '89' '92' '95' '98' '101' '104' '107' '110' '113')
line_number_H1=('118' '121' '124' '127' '130' '133')
line_number_H2=('138' '141' '144' '147' '150' '153')

zeros="     0.00000000  0.00000000  0.00000000  0.00000000  0.00000000"


for ((job=1;job<=2.0;job++));
do
output=~/interpolate/grid_1_11_15/aiff/m$job.freq_pol

    for ((i=1;i<=36;i++));
    do
    holder=$line_number_O[i]
    tmp=$(sed -n "${holder}p" $output)

        if [[ $tmp != $freq_pols[i] ]];then
        #echo $tmp
        awk -v n=$holder -v s=$zeros 'NR == n {print s} {print}' $output > test
        awk -v n=$holder -v s=$freq_pols[i] 'NR == n {print s} {print}' $output > test
        fi

    done


done

示例输入:

Title monomer ... monomer
Frequencies   0.5    10
Skip  0
Print nonzero
Molecule  monomer
Site  O1  type  O1
10 10
 7.16240000      7.13140000      6.95110000      6.37710000      5.16380000
 3.41180000      1.74320000      0.64940000      0.12840000      0.00480000
10 11s
-0.78000000     -0.77400000     -0.74000000     -0.64100000     -0.45000000
-0.22200000     -0.09000000     -0.03200000     -0.00500000      0.00000000
.....

示例输出:

Title monomer ... monomer
Frequencies   0.5    10
Skip  0
Print nonzero
Molecule  monomer
Site  O1  type  O1
10 10
 7.16240000      7.13140000      6.95110000      6.37710000      5.16380000
 3.41180000      1.74320000      0.64940000      0.12840000      0.00480000
**10 11c**
**0.0000000      0.00000000     0.00000000     0.00000000     0.0000000**
**0.0000000      0.00000000     0.00000000     0.00000000     0.0000000**
10 11s
-0.78000000     -0.77400000     -0.74000000     -0.64100000     -0.45000000
-0.22200000     -0.09000000     -0.03200000     -0.00500000      0.00000000
.....

粗体文字是我想添加的内容。 (现在由**字符包围的粗体文字:Shellter)

1 个答案:

答案 0 :(得分:0)

我会选择sedHere您可以看到一个可能适合您的示例。 鉴于当您附加到文件时,行号可能会更改,您应该在反向行号中附加。