linux中awk命令实现一列数据按照标题折叠及展开
1、测试 数据
[root@centos7 test2]# ls
a.txt
[root@centos7 test2]# cat a.txt
T1
person1
person2
person3
T2
person1
person2
T3
person1
person2
person3
person4
2、折叠
[root@centos7 test2]# cat a.txt T1 person1 person2 person3 T2 person1 person2 T3 person1 person2 person3 person4 [root@centos7 test2]# awk '{if($0 ~ /^T/) {team = $0} else {print team, $0}}' a.txt T1 person1 T1 person2 T1 person3 T2 person1 T2 person2 T3 person1 T3 person2 T3 person3 T3 person4
3、展开
[root@centos7 test2]# ls a.txt b.txt [root@centos7 test2]# cat b.txt T1 person1 T1 person2 T1 person3 T2 person1 T2 person2 T3 person1 T3 person2 T3 person3 T3 person4 [root@centos7 test2]# awk '{print $1}' b.txt | sort -u | while read i; do awk -v a=$i 'BEGIN{print a}{if($1 == a){print $2}}' b.txt >> result.txt; done [root@centos7 test2]# ls a.txt b.txt result.txt [root@centos7 test2]# cat result.txt T1 person1 person2 person3 T2 person1 person2 T3 person1 person2 person3 person4