Original title: https://leetcode.com/problems/transpose-file/
Given a textfile file. txt, transpose its content. You may assume this each row have the same number of columns and each field are separated by the' 'character. For example,if file. txt has the following content:name agealice +Ryan -Output the Following:name Alice Ryanage + 30
The simple meaning is that there is a file content in each line separated by a space, and the number of rows and columns equal, please output, the first column as the first row, the second column as the second row, White is the row and column conversion .
Store all the content in a two-dimensional array, and then output each row by column.
Answer:
Cat file. txt| awk ' begin{c=0;} {for (i=1;i<=nf;i++) {num[c,i] = $i;} c + +;} end{for (i=1;i<=nf;i++) {str= ""; for (j=0;j<nr;j++) {if (j>0) {str = str ""} str= str "" num[j,i]}printf ("%s\n", str )}}'
The awk command is used, and in awk there is a begin (start), End (end), NF (number of columns, starting from 1), NR (number of rows, starting from 1).
Concatenation of strings, such as Str=str "" Num[j,i.
Shell practice row and column conversions