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
知识点:awk
awk ' ' file: ' ' 中是处理语句
BEGIN {
# 执行之前的操作,一般是赋值
}
{
# 中间是对每一行的操作
}
END {
# 处理完后的操作,一般是格式化输出
}
解法:用一个数组s,里面有NF个元素,其中NF(列号)是当前记录的总字数。对于第一个记录,直接存到相应的s[i]中,最后s[i[对应源文件一列的内容。
#!/bin/bash awk 'BEGIN{}
{
for(i = ; i <= NF; i++){
if (NR == ){
s[i]=$i;
}
else{
s[i]=s[i]" "$i;
}
}
}END{
for(i = ; i <= NF; i++){
print s[i];
}
}' file.txt