★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-buhwxput-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a text file file.txt
, transpose its content.git
You may assume that each row has the same number of columns and each field is separated by the ' '
character.github
Example:bash
If file.txt
has the following content:微信
name age alice 21 ryan 30
Output the following:spa
name alice ryan age 21 30
給定一個文件 file.txt
,轉置它的內容。code
你能夠假設每行列數相同,而且每一個字段由 ' '
分隔.htm
示例:blog
假設 file.txt
文件內容以下:get
name age alice 21 ryan 30
應當輸出:
name alice ryan age 21 30
12ms
1 # Read from the file file.txt and print its transposed content to stdout. 2 3 awk ' 4 BEGIN { hasBegan = 0 } 5 { 6 if (hasBegan == 0) { 7 for (ii = 1; ii <= NF; ii += 1) { 8 arr[ii] = $ii; 9 } 10 hasBegan = 1; 11 } else { 12 for (ii = 1; ii <= NF; ii += 1) { 13 arr[ii] = arr[ii]" "$ii; 14 } 15 } 16 } 17 END { 18 for (ii = 1; ii <= length(arr); ii += 1) { 19 print arr[ii]; 20 } 21 } 22 ' file.txt
136ms
1 #!/bin/bash 2 # Read from the file file.txt and print its transposed content to stdout 3 4 lines=() 5 6 while read line 7 do 8 i=0 9 for word in $line 10 do 11 if (( ${#lines[i]} > 0 )); then lines[i]+=" "; fi 12 lines[i]+="$word" 13 ((i++)) 14 done 15 done < "file.txt" 16 17 last=$((${#lines[@]}-1)) 18 19 for k in $(seq 0 $last) 20 do 21 echo "${lines[$k]}" 22 done
168ms
1 # Read from the file file.txt and print its transposed content to stdout. 2 while read -a line; do 3 for ((i = 0; i < "${#line[@]}"; ++i)); do 4 a[$i]="${a[$i]} ${line[$i]}" 5 done 6 done < file.txt 7 for ((i = 0; i < ${#a[@]}; ++i)); do 8 echo ${a[i]} 9 done