Bash Shell脚本转置矩阵无法打印

时间:2019-10-13 23:11:54

标签: bash shell

我正在编写一个bash shell脚本,它必须执行多项操作。我当前正在使用的功能需要转置矩阵,在这种情况下,该矩阵只是具有行和列的文本文件。我有两个文件,分别称为m1和m2 ... m1文本文件就是这样:

1 2 3
4 5 6

m2 =

1 5
2 6
3 7
4 8

所以本质上我需要将m2变成m1并将m1变成m2。到目前为止,这是我的代码,我大部分是从有关移调的课堂演讲中获得的,这很有帮助。它目前没有打印出任何东西,但是它仍然可以运行并且没有运行时错误。

这是我的代码:

transpose)

inputFile="tempinputfile"
tempCol="tempcolfile"
tempRow="temprowfile"


echo -e "1\t2\t3\t4\t5" > $inputFile

cut -c 1 $inputFile > $tempCol
cut -c 3 $inputFile >> $tempCol
cut -c 5 $inputFile >> $tempCol
cut -c 7 $inputFile >> $tempCol
cut -c 9 $inputFile >> $tempCol

cat $tempCol | tr '\n' '\t' > "$tempRow$$"

echo >> "$tempRow$$"




;;

2 个答案:

答案 0 :(得分:0)

您是否使用过二维数组?一旦将数据加载到数组中(例如arr [x,y]),“转置”操作将只包含遍历y和x索引。

我发现awk中的数组比bash中的数组更容易使用;这是一个awk提示:

awk '

BEGIN { arr[1][1]="a" ; arr[1][2]="b"
        arr[2][1]="c" ; arr[2][2]="d"
      }

END { printf "+++++++++++ as is\n"
      for (x in arr)
          { for (y in arr[x])
                { printf "%s ",arr[x][y] }
            printf "\n"
          }
      printf "+++++++++++ transposed\n"
      for (x in arr)
          { for (y in arr[x])
                { printf "%s ",arr[y][x] }
            printf "\n"
          }
      printf "+++++++++++\n"
    }
' m1

+++++++++++ as is
a b
c d
+++++++++++ transposed
a c
b d
+++++++++++

在您的情况下,您想用用文件中的数据填充数组(BEGIN)的代码替换整个arr[][]块;另一个提示:查找awk变量'NF'和'NR'。

基于awk的解决方案还有一个好处,就是它只扫描输入文件一次;而且由于文件IO会产生(相对)较高的开销,因此处理文件的次数越少,代码的运行速度就越快。

答案 1 :(得分:0)

awk '{ for (i=1; i<=NF; i++) a[i]=(a[i]? a[i] FS $i: $i) } END{ for (i in a) print a[i] }' file.txt