我在 Linux 系统上有一个包含 3 列的文件(以逗号分隔)。我想在每第四行之后开始新的列。
输入:
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 行输出,每行都是用逗号连接输入的每第四行的结果。
答案1
和awk
:
awk '{a[NR%4] = a[NR%4] (NR<=4 ? "" : ",") $0}
END{for (i = 1; i <= 4; i++) print a[i%4]}' < input.txt
答案2
尝试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"