Linux 中 awk 利用外部文件传入数字变量,利用循坏提取特定列

 

Linux 中 awk 利用外部文件传入数字变量,利用循坏提取特定列

 

001、awk实现

[root@PC1 test]# ls
a.txt  test.txt
[root@PC1 test]# cat a.txt                    ## 索引文件
2
5
6
8
[root@PC1 test]# cat test.txt                 ## 测试文本
1       2       3       4       5       6       7       8       9
a       b       c       d       e       f       g       h       i
[root@PC1 test]# var=""
[root@PC1 test]# for i in $(cat a.txt); do var="$var,$i"; done    ## 将所有索引保存在一个变量中
[root@PC1 test]# var=${var:1}
[root@PC1 test]# echo $var
2,5,6,8
[root@PC1 test]# awk -v x=$var 'BEGIN{n=split(x,a,",")}{for(i = 1; i <= n; i++) {printf "%s%s", $a[i], i<n?"\t":"\n"}}' test.txt      ## 利用awk提取数据
2       5       6       8
b       e       f       h

 

image

 。

 

002、更简洁的做法

[root@PC1 test]# ls
a.txt  test.txt
[root@PC1 test]# cat a.txt         ## 索引文件
2
5
6
8
[root@PC1 test]# cat test.txt      ## 测试文本
1       2       3       4       5       6       7       8       9
a       b       c       d       e       f       g       h       i
[root@PC1 test]# awk '{if(NR == FNR){ay1[++n]=$1}else{for(i = 1; i <= n; i++) {printf "%s%s",$ay1[i],i<n?"\t":"\n"}}}' a.txt test.txt   ## awk提取数据
2       5       6       8
b       e       f       h

image

 。

 

posted @ 2026-01-05 20:12  小鲨鱼2018  阅读(2)  评论(0)    收藏  举报