Transpose File
Total Accepted: 3876
Total Submissions: 18849
Difficulty: Medium
Contributors: Admin
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.
For example, if file.txt has the following content:
name age
alice 21
ryan 30
Output the following:
name alice ryan
age 21 30
解法一:
利用NF个数组进行存储,就是每次遍历一个记录的时候,把第一列放到数组line[1]中,第二列放到数组lien[2]中.....
接下来遍历的时候,然后继续向line[1],line[2]....的后面接数据
代码:
#!/bin/ksh
typeset number
gawk '{
for( i=1;i<=NF;i++)
{
if (str[i] == "")
{
str[i]=$i
}
else
{
str[i]=str[i]" "$i
}
}
}
END{
for(i=1;i<=NF;i++)
{
print str[i]
}
number=NF
}
' t12-file.txt
# out of the awk,the value of the number is null, not the value of NF
print "The number is $number"
解法二:
利用cut直接打印出第一列,第二列.....
在cut外定义的变量,可以传进到cut中,既可以在cut中使用cut外面定义和赋值的变量;
同是在cut中对变量的新赋值,也能在cut外面反映出来。
代码:
#! /bin/ksh
typeset number
number=$(awk '{num=NF} END{print num}' t12-file.txt)
for ((i=1;i<=$number;i++ )); do
print "This is the \$i: $i"
cut -d " " -f $i t12-file.txt |xargs
num="hello world"
done
# the value of num is "hello world"
print "The num is $num"
解法三:
利用估计列数的办法,不好的办法。
awk外面定义的变量不能在awk中使用,除非把值传进awk中,否则,在外面定义的变量,在awk中使用是空的。
同理,在awk中改变变量的值,在awk外面也不能反映出来。
代码:
#!/bin/ksh
awk -F" " 'BEGIN{i=1}{print $i}' t12-file.txt |xargs
awk -F" " 'BEGIN{i=2} {print $i}' t12-file.txt |xargs
print "################################"
i=1
awk -F" " '{print $field}' field=$i t12-file.txt |xargs
((i++))
awk -F" " '{print $field}' field=$i t12-file.txt |xargs