当前位置: 首页> 财经> 金融 > LeetCode //Bash - 194. Transpose File

LeetCode //Bash - 194. Transpose File

时间:2025/7/12 4:56:39来源:https://blog.csdn.net/navicheung/article/details/140090780 浏览次数:0次

194. Transpose File

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.
 

Example:

If file.txt has the following content:
name age
alice 21
ryan 30
Output the following:
name alice ryan
age 21 30

From: LeetCode
Link: 194. Transpose File


Solution:

Ideas:
  1. Reading lines and columns: awk processes the file line by line. For each field in the line, it appends the field to the corresponding index in the transposed array.

  2. Constructing the transposed lines: As we read each line, we concatenate the fields to build the transposed rows. The NR variable tracks the line number.

  3. Printing the transposed result: After processing all lines (END block), we print each element of the transposed array.

Code:
# Read from the file file.txt and print its transposed content to stdout.awk '
{for (i = 1; i <= NF; i++) {if (NR == 1) {transposed[i] = $i} else {transposed[i] = transposed[i] " " $i}}
}
END {for (i = 1; i <= NF; i++) {print transposed[i]}
}' file.txt
关键字:LeetCode //Bash - 194. Transpose File

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: