linux 中实现批量抽取指定的行

发布时间 2023-10-11 22:23:45作者: 小鲨鱼2018

 

001、测试数据

[root@pc1 test1]# ls
a.txt  index.txt
[root@pc1 test1]# cat a.txt           ## 测试文件
01 02 1
03 04 2
05 06 3
07 08 4
09 10 5
11 12 6
13 14 7
15 16 8
17 18 9
19 20 10
21 22 11
23 24 12
25 26 13
[root@pc1 test1]# cat index.txt      ## 抽取索引
2 4
5 8
9 12

 

002、方法1 借助循环 + sed实现

[root@pc1 test1]# ls
a.txt  index.txt                                                ## 批量抽取
[root@pc1 test1]# cat index.txt | while read {i,j}; do sed -n "$i, $j"p a.txt >> result.txt; done
[root@pc1 test1]# ls
a.txt  index.txt  result.txt
[root@pc1 test1]# cat result.txt         ## 结果文件
03 04 2
05 06 3
07 08 4
09 10 5
11 12 6
13 14 7
15 16 8
17 18 9
19 20 10
21 22 11
23 24 12
[root@pc1 test1]# cat index.txt           ## 索引行
2 4
5 8
9 12

 

003、循环 + awk实现