LeetCode Solution, Medium, 194. Transpose File

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

題目翻譯

翻轉資料,將原本的行列互換。

解法解析

這邊是先使用 head -1 file.txt | wc -w | xargs seq 1 找出說總共有多少個欄位。之後將其結果當作參數,利用 xargs 丟到 cut -d ' ' -f{} file.txt | paste -sd ' ' - 將其翻轉。

解法範例

Bash
# Read from the file file.txt and print its transposed content to stdout.
head -1 file.txt | wc -w | xargs seq 1 | xargs -I{} -n 1 sh -c "cut -d ' ' -f{} file.txt | paste -sd ' ' -"