поворот колонки в awk - PullRequest
       6

поворот колонки в awk

2 голосов
/ 03 февраля 2020

У меня есть следующий текстовый файл

cat file.txt

name        value
ID1         a;b;c
ID2         d
ID3         e;f

Я хотел бы повернуть их.

Желаемый выход

name        value
ID1         a
ID1         b
ID1         c
ID2         d
ID3         e
ID3         f

Я думал

txt.awk

BEGIN { FS=OFS="\t" }

NR>1 {
     a=$1 split($2,a,";"); next
}

NR>1 {
     a=$1 for (i in a)
          print a, a[i]
     printf "\n"
}

, но это не в состоянии инициировать массивы. Есть ли альтернатива?

1 Ответ

5 голосов
/ 03 февраля 2020

РЕДАКТИРОВАТЬ: В соответствии с предложением Эд сэр, добавив следующее решение.

awk '
BEGIN{
  OFS="\t\t"
}
FNR==1{
  print
  next
}
{
  num=split($2,array,/;/)
  for(i=1;i<=num;i++){
    print $1,array[i]
  }
}
'  Input_file

Не могли бы вы попробовать следующее.

awk '
BEGIN{
  OFS="\t\t"
}
FNR==1{
  print
  next
}
{
  num=split($2,array,";")
  for(i=1;i<=num;i++){
    print $1,array[i]
  }
  delete array
}
'  Input_file

Вывод будет следующим:

name        value
ID1             a
ID1             b
ID1             c
ID2             d
ID3             e
ID3             f

Объяснение: Добавление подробного объяснения для вышеуказанного кода.

awk '                          ##Starting awk program from here.
BEGIN{                         ##Starting BEGIN section from here.
  OFS="\t\t"                   ##Setting OFS as 2 times TAB for all lines here.
}                              ##Closing BEGIN section of this code here.
FNR==1{                        ##Checking condition if line is first line then do following.
  print                        ##Printing current line here.
  next                         ##next will skip all further statements from here.
}                              ##Closing FNR==1 condition BLOCK of this program here.
{
  num=split($2,array,";")      ##Splitting 2nd field into an array named array whose delimiter is semi-colon and total number of elements will save into num variable.
  for(i=1;i<=num;i++){         ##Starting a for loop from i=1 to till value of num variable here.
    print $1,array[i]          ##Printing first field and value of array with index of variable i here.
  }
  delete array                 ##Deleting array here.
}
'  Input_file                  ##Mentioning Input_file name here.
...