Text-Processing

將文本文件數據轉換為表格

  • December 24, 2020

我有一個包含 2 列的文本文件,我想將其轉換為表格。下圖只是文件中的樣子,而不是表格。格式是在發布問題時將我的所有文本放在一行中。

這是文件中數據的樣子:

name: name1
copies: 3
copy1: name1copy1
copy2: name1copy2
copy3: name1copy3
name: name2
copies: 1
copy1: name2copy1
name: name3
copies: 2
copy1: name3copy1
copy2: name3copy2 

這就是我想擺脫的:

name,copies,copy1,copy2,copy3  
name1,3,name1copy1,name1copy2,name1copy3
name2,1,name2copy1,bull,null
name3,2,name3copy1,name3copy2,null  

從這裡我可以導入到excel中。

這將 GNU awk 用於多維數組:它一次讀取所有數​​據並在 END 塊中發出輸出。這是“script.awk”

BEGIN {FS = ": "}

!($1 in head) {head[$1] = h++}
$1 == "name"  {name = $2}
{data[name][$1] = $2}

END {
   PROCINFO["sorted_in"] = "@val_num_asc"

   # print the header
   sep=""
   for (item in head) {
       printf "%s%s", sep, item
       sep = ","
   }
   printf "\n"

   # print the data
   for (name in data) {
       sep=""
       for (item in head) {
           printf "%s%s", sep, data[name][item]
           sep = ","
       }
       printf "\n"
   }
}

然後:

$ gawk -f script.awk file
name,copies,copy1,copy2,copy3
name1,3,name1copy1,name1copy2,name1copy3
name2,1,name2copy1,,
name3,2,name3copy1,name3copy2,

引用自:https://unix.stackexchange.com/questions/625951