================ 文件内容列传行_行转列 ================
一、列转行
1、编辑测试文件
vi log.txt
16:23:00
8.2%
1773620k
16:23:01
3%
1770024k
16:23:02
5.7%
1766272k
16:23:03
4%
1766160k
16:23:04
7.9%
1775436k
16:23:05
2.5%
1775488k
16:23:06
3.9%
1770340k
2、编辑列转行脚本
vi colline.sh
sh colline.sh log.txt
输出:
16:23:00 8.2% 1773620k
16:23:01 3% 1770024k
16:23:02 5.7% 1766272k
16:23:03 4% 1766160k
16:23:04 7.9% 1775436k
16:23:05 2.5% 1775488k
16:23:06 3.9% 1770340k
二、行转列
1、编辑测试文件
vi f.txt
1 2 3 4 5
1 2 3 4 6
1 2 3 4 7
1 2 3 4 8
1 2 3 4 9
2 3 4 5 10
7 8 9 10 11
12 13 14 15 16
2、运行列转行_行转列命令
awk ‘{for(i=1;i<=NF;i++)a[NR,i]=$i}END{for(j=1;j<=NF;j++)for(k=1;k<=NR;k++)printf k==NR?a[k,j] RS:a[k,j] FS}‘ f.txt
输出:
1 1 1 1 1 2 7 12
2 2 2 2 2 3 8 13
3 3 3 3 3 4 9 14
4 4 4 4 4 5 10 15
5 6 7 8 9 10 11 16
备注:文件至少需要两列数据
===== 文件内容输出为一行
编辑文件:
vi file.txt
1 2 3 4 5 6
a b c d e f
2 3 4 5 6 7
q a z w s x
3 4 5 6 7 8
awk -F "+" ‘{for(i=1;i<=NF;i++) a[i,NR]=$i}END{for(i=1;i<=NF;i++) {for(j=1;j<=NR;j++) printf a[i,j] " ";print ""}}‘ file.txt
输出:
1 2 3 4 5 6 a b c d e f 2 3 4 5 6 7 q a z w s x 3 4 5 6 7 8
cat file.txt |tr "\n" ","|sed -e ‘s/,$/\n/‘
输出:
1 2 3 4 5 6,a b c d e f,2 3 4 5 6 7,q a z w s x,3 4 5 6 7 8
cat file.txt |tr "\n" " "|sed -e ‘s/,$/\n/‘
输出:
1 2 3 4 5 6 a b c d e f 2 3 4 5 6 7 q a z w s x 3 4 5 6 7 8
--->行转列_列转行
vi test.txt
1 2 3 4 5 6 7 8
awk -F " +" ‘{for(i=1;i<=NF;i++) a[i,NR]=$i}END{for(i=1;i<=NF;i++) {for(j=1;j<=NR;j++) printf a[i,j] " ";print ""}}‘ test.txt
输出:
1
2
3
4
5
6
7
8
vi test.txt
1
2
3
4
5
6
7
8
awk -F " +" ‘{for(i=1;i<=NF;i++) a[i,NR]=$i}END{for(i=1;i<=NF;i++) {for(j=1;j<=NR;j++) printf a[i,j] " ";print ""}}‘ test.txt
输出:
1 2 3 4 5 6 7 8
<end>