循环中的打印语句

时间:2015-09-08 02:06:36

标签: linux shell unix awk printf

我有几个名为file1.txt,file2.txt的文本文件,依此类推。 我想在给出一些重量之后打印每个文件的平均值。我的脚本是

#!/bin/sh
m1=3.2; m2=1.2; m3=0.2   #mean of file1.txt, file2.txt ...
for i in {1..100}   #files
  do for j in 20 30 35 45   #weightages 
    do
      k=m$i*$j  #This is an example, calulated as mean of file$i.txt * j
      printf "%5s %8.3f\n" "$i" "$k" >> ofile.txt
    done
  done

以上打印为

ofile.txt
1    64
1    96
1    112
1    144
2    24
2    36
.    .

希望输出格式为

ofile.txt
1    64   96   112   144
2    24   36   42    54
3    4    6    7     9
.     .    .    .     .

其中第一列是文件号,第二列,第三列,第四列是m * j

2 个答案:

答案 0 :(得分:1)

#!/bin/sh
m1=3.2; m2=1.2; m3=0.2   #mean of file1.txt, file2.txt ...
for i in {1..100}   #files
  ofile_line="$i "
  do for j in 20 30 35 45   #weightages 
    do
      k=m$i*$j  #This is an example, calulated as mean of file$i.txt * j
      support=$(printf "%5s %8.3f\n" "$i" "$k")
      ofile_line="${ofile_line}${support} "
    done
   echo "${ofile_line}" >> ofile.txt
  done

您不需要\n来回"${ofile_line}" >> ofile.txt,因为echo会为您打破这一行。

答案 1 :(得分:1)

离开我的头顶,所以你可能需要纠正一些东西。

#!/bin/sh
m1=3.2; m2=1.2; m3=0.2   #mean of file1.txt, file2.txt ...
for i in {1..100}   #files
  do
    printf "%5s" "$i" >> ofile.txt
    for j in 20 30 35 45   #weightages 
      do
        k=m$i*$j  #This is an example, calulated as mean of file$i.txt * j
        printf "\t%8.3f" "$k" >> ofile.txt
      done
    printf "\n" >> ofile.txt
  done