将行转置为列,使一些行在shell

时间:2019-06-10 00:58:40

标签: unix awk

我有一个需要转置的文件,看起来像这样:

Person ID| commute to work in hours?| Happiness score?| work satisfaction score?
1234| 2 | 8 | 7
5678| 1 | 7 | 6
6789| 0.5 | 9 | 6

我需要按如下所示进行枢纽操作:

Person ID | Question | Answer
1234 | commute to work in hours? | 2
1234 | Happiness score? | 8
1234 | work satisfaction score? | 7
5678 | commute to work in hours? | 1
5678 | Happiness score? | 7
5678 | work satisfaction score? | 6
6789 | commute to work in hours? | 0.5
6789 | Happiness score? | 9
6789 | work satisfaction score? | 6

我尝试使用awk,并且能够获得:

1234 | 3
1234 | 8
1234 | 7
5678 | 1
5678 | 7
5678 | 6
6789 | 0.5
6789 | 9
6789 | 6

但是我无法添加问题。

awk '{
   for(i=2;i<=NF;i++) 
       unique[$1]=(unique[$1]FS$i); next } END { 
  for (i in unique) { 
       n=split(unique[i],temp); 
       for(j=1;j<=n;j++) 
           print i,temp[j] } }' file

3 个答案:

答案 0 :(得分:2)

如果只有三个字段,则不需要使用循环,因此应该可以使用。

onStart

答案 1 :(得分:1)

输入:

$ cat file_transpose 
Person ID| commute to work in hours?| Happiness score?| work satisfaction score?
1234| 2 | 8 | 7
5678| 1 | 7 | 6
6789| 0.5 | 9 | 6

输出:

$ awk 'BEGIN{FS="|";OFS=" |"}NR==1{for(i=2;i<=NF;i++){buff[i]=$i};print "Person ID | Question | Answer";next}{for(i=2;i<=NF;i++){print $1,buff[i],$i}}' file_transpose 
Person ID | Question | Answer
1234 | commute to work in hours? | 2 
1234 | Happiness score? | 8 
1234 | work satisfaction score? | 7
5678 | commute to work in hours? | 1 
5678 | Happiness score? | 7 
5678 | work satisfaction score? | 6
6789 | commute to work in hours? | 0.5 
6789 | Happiness score? | 9 
6789 | work satisfaction score? | 6

说明:

#field separator and output field separator
BEGIN {
       FS = "|"
       #you might want to remove the space
       OFS = " |"
}

# Rule(s)
# On the first line, save all the questions in buff, print the header, jump to next line
NR == 1 { 
       for (i = 2; i <= NF; i++) {
            buff[i] = $i
       }
       print "Person ID | Question | Answer"
       next
 }
 #for the rest of the file, print the first field, each question and associated answer
 {
       for (i = 2; i <= NF; i++) {
           print $1, buff[i], $i
       }
 }

答案 2 :(得分:1)

|A[i]| < array length