Shell

如何在每第 n 行之後開始一個新列?

  • June 4, 2020

我在具有 3 列的 Linux 系統上有一個文件(逗號分隔)。我想在每 4 行之後開始新列。

輸入:

col1,col2,col3 
1,disease1,high
1,disease2,low 
1,disease3,high
col1,col2,col3 
2,disease1,low 
2,disease2,low 
2,disease3,high
col1,col2,col3
3,disease1,low
3,disease2,low
3,disease3,low

預期輸出:

col1,col2,col3,col1,col2,col3,col1,col2,col3
1,disease1,high,2,disease1,low,3,disease1,low
1,disease2,low,2,disease2,low,3,disease2,low
1,disease3,high,2,disease3,high,disease3,low

即我想要4行輸出,每行是輸入的每第四行用逗號連接的結果。

awk

awk '{a[NR%4] = a[NR%4] (NR<=4 ? "" : ",") $0}
    END{for (i = 1; i <= 4; i++) print a[i%4]}' < input.txt

嘗試將paste四行read合二為一,將它們分為四個變數,將每個變數附加到輸出行:

paste -s -d"   \n" file | 
{ while read A B C D 
   do  L1="$L1$DL$A"
       L2="$L2$DL$B"
       L3="$L3$DL$C"
       L4="$L4$DL$D"
       DL=, 
   done 
 printf "%s\n" "$L1" "$L2" "$L3" "$L4"  
}
col1,col2,col3,col1,col2,col3,
1,disease1,high,2,disease1,low,
1,disease2,low,2,disease2,low,
1,disease3,high,2,disease3,high,

**編輯:**或者,更簡單一點,paste不需要:

while read A && read B && read C && read D     
 do    L1="$L1$DL$A"
       L2="$L2$DL$B"
       L3="$L3$DL$C"
       L4="$L4$DL$D"
       DL=,     
 done < file 
printf "%s\n" "$L1" "$L2" "$L3" "$L4"

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