Linux Shell 统计一(行\列)数值的总和及行、列转换
(对一列数字求和)
在日常工作当中需要对文本过滤出来的数字进行求和运算,例如想统计一个MySQL分区表现在有多大
# ls -lsh AdPlateform#P#p*.ibd |grep G
2.6G -rw-rw---- 1 mysql mysql 2.6G Mar 4 01:05 AdPlateform#P#p20200304.ibd
2.9G -rw-rw---- 1 mysql mysql 2.9G Mar 5 01:12 AdPlateform#P#p20200305.ibd
# ls -lsh AdPlateform#P#p*.ibd |grep G|awk '{sum+=$6} END{print "sum="sum}'
sum=5.5
(对一行数字求和)
在日常工作当中需要对一行文本进行求和运算
# cat 1.txt
1 2 3 4 5 6 7 8 9 10
# cat 1.txt |awk '{for(i=1;i<=NF;i++) sum+=$i} END{print "sum="sum}'
sum=55
(行转列)
# cat 1.txt
1 2 3 4 5 6 7 8 9 10
# 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}' 1.txt
1
2
3
4
5
6
7
8
9
10
(列转行)
# cat 2.txt
1
2
3
4
5
6
7
8
9
10
# cat 2.txt |tr "\n" ","|sed -e 's/,$/\n/'|tr "," " "
1 2 3 4 5 6 7 8 9 10
(取出ip字段的前几列)
# echo "10.10.33.161.62342" |awk -F'.' {'print $1,$2,$3,$4'}|tr " " "."
10.10.33.161