linux系统中awk命令for循环提取文件的连续列


 

1、测试数据

[root@centos7 test2]# cat a.txt
e d g e d w i
s d g w e i d
a x d g i w e
n d i d o e w

 

2、提取1-3列,1-5列

[root@centos7 test2]# cat a.txt e d g e d w i s d g w e i d a x d g i w e n d i d o e w [root@centos7 test2]# awk '{for (i = 1; i <= 3; i++) printf("%s ", $i); printf("\n")}' a.txt e d g s d g a x d n d i [root@centos7 test2]# awk '{for (i = 1; i <= 5; i++) printf("%s ", $i); printf("\n")}' a.txt e d g e d s d g w e a x d g i n d i d o

 

3、提取1-3列加第6列,1-3列加5-6列

[root@centos7 test2]# cat a.txt e d g e d w i s d g w e i d a x d g i w e n d i d o e w [root@centos7 test2]# awk '{for(i = 1; i <= 3; i++) printf("%s ", $i); print $6}' a.txt e d g w s d g i a x d w n d i e [root@centos7 test2]# awk '{for(i = 1; i <= 3; i++) printf("%s ", $i); print $5,$6}' a.txt e d g d w s d g e i a x d i w n d i o e

 

4、提取奇数列

[root@centos7 test2]# cat a.txt 1 2 3 4 5 6 7 e d g e d w i s d g w e i d a x d g i w e n d i d o e w [root@centos7 test2]# awk '{for (i = 1; i <= NF; i+=2) printf("%s ", $i); printf("\n")}' a.txt 1 3 5 7 e g d i s g e d a d i e n i o w [root@centos7 test2]# awk '{for (i = 1; i <= NF; i++) if (i % 2 != 0) printf("%s ", $i); printf("\n")}' a.txt 1 3 5 7 e g d i s g e d a d i e n i o w

 

5、提取偶数列

[root@centos7 test2]# cat a.txt 1 2 3 4 5 6 7 e d g e d w i s d g w e i d a x d g i w e n d i d o e w [root@centos7 test2]# awk '{for(i = 2; i <= NF; i+=2) printf("%s ", $i); printf("\n")}' a.txt 2 4 6 d e w d w i x g w d d e [root@centos7 test2]# awk '{for(i = 1; i <= NF; i++) if (i % 2 == 0) printf("%s ", $i); printf("\n")}' a.txt 2 4 6 d e w d w i x g w d d e

 

5、提取3倍数列

[root@centos7 test2]# cat a.txt 1 2 3 4 5 6 7 e d g e d w i s d g w e i d a x d g i w e n d i d o e w [root@centos7 test2]# awk '{for (i = 1; i <= NF; i++) if (i % 3 == 0) printf("%s ", $i); printf("\n")}' a.txt 3 6 g w g i d w i e

 

6、提取倒数后4列、后5列

[root@centos7 test2]# cat a.txt 1 2 3 4 5 6 7 e d g e d w i s d g w e i d a x d g i w e n d i d o e w [root@centos7 test2]# awk '{for (i = NF - 3; i <= NF; i++) printf("%s ", $i); printf("\n")}' a.txt 4 5 6 7 e d w i w e i d g i w e d o e w [root@centos7 test2]# awk '{for (i = NF - 4; i <= NF; i++) printf("%s ", $i); printf("\n")}' a.txt 3 4 5 6 7 g e d w i g w e i d d g i w e i d o e w

 

7、去倒数5列中的偶数列

[root@centos7 test2]# cat a.txt 1 2 3 4 5 6 7 e d g e d w i s d g w e i d a x d g i w e n d i d o e w [root@centos7 test2]# awk '{for (i = NF - 4; i <= NF; i++) if (i % 2 == 0) printf("%s ", $i); printf("\n")}' a.txt 4 6 e w w i g w d e

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM