Given a text file file.txt
, transpose its content.
You may assume that each row has the same number of columns and each field is separated by the ' '
character.
For example, if file.txt
has the following content:
name age alice 21 ryan 30
Output the following:
name alice ryan age 21 30
题意:从file.txt中读取数据,相当于调换行和列,将列变成行
思路:主要用了read -a来读取数据到数组中,以及涉及到数组的操作,如${#array_name[@]}表示数组array_name的长度,数组元素的引用${array_name[i]}表示数组array_name的第i个元素(下标从0开始)
代码如下:
while read -a columns #读取一行到数组columns中 do for ((i=0; i < ${#columns[@]}; i++)) # ${#columns[@]}表示数组长度 do a[i]="${a[i]} ${columns[i]}" done done < file.txt for ((i=0; i < ${#a[@]};i++)) do echo ${a[i]} done