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