linux中如何使用变量提取连续的行

1、一般情况提取连续行

测试数据

root@PC1:/home/test2# ls
test.txt
root@PC1:/home/test2# cat test.txt
>1 01 02
>2 03 04
>3 05 06
>4 07 08
>5 09 10
>6 11 12
>7 13 14
>8 15 16
>9 17 18
>10 19 20

 

2、sed实现,提取2到5行

root@PC1:/home/test2# ls
test.txt
root@PC1:/home/test2# cat test.txt
>1 01 02
>2 03 04
>3 05 06
>4 07 08
>5 09 10
>6 11 12
>7 13 14
>8 15 16
>9 17 18
>10 19 20
root@PC1:/home/test2# sed -n '2,5p' test.txt
>2 03 04
>3 05 06
>4 07 08
>5 09 10

 

3、awk实现

root@PC1:/home/test2# ls
test.txt
root@PC1:/home/test2# cat test.txt
>1 01 02
>2 03 04
>3 05 06
>4 07 08
>5 09 10
>6 11 12
>7 13 14
>8 15 16
>9 17 18
>10 19 20
root@PC1:/home/test2# awk 'NR == 2, NR == 5' test.txt
>2 03 04
>3 05 06
>4 07 08
>5 09 10

 

4、当行数为变量时,sed不起作用

root@PC1:/home/test2# ls
test.txt
root@PC1:/home/test2# cat test.txt
>1 01 02
>2 03 04
>3 05 06
>4 07 08
>5 09 10
>6 11 12
>7 13 14
>8 15 16
>9 17 18
>10 19 20
root@PC1:/home/test2# a=2
root@PC1:/home/test2# b=5
root@PC1:/home/test2# echo $a
2
root@PC1:/home/test2# echo $b
5
root@PC1:/home/test2# sed -n "$a,$bp" test.txt     ## sed使用变量提取连续行报错
sed: -e expression #1, char 2: unexpected `,'
root@PC1:/home/test2# sed -n '$a,$bp' test.txt     ## 同上
,$bp
root@PC1:/home/test2# echo $a
2
root@PC1:/home/test2# echo $b
5

 

5、awk命令实现利用变量提取连续行

root@PC1:/home/test2# ls
test.txt
root@PC1:/home/test2# cat test.txt
>1 01 02
>2 03 04
>3 05 06
>4 07 08
>5 09 10
>6 11 12
>7 13 14
>8 15 16
>9 17 18
>10 19 20
root@PC1:/home/test2# a=2
root@PC1:/home/test2# b=5
root@PC1:/home/test2# echo $a
2
root@PC1:/home/test2# echo $b
5
root@PC1:/home/test2# awk -v v1=$a -v v2=$b 'NR == v1, NR == v2' test.txt  ## awk命令可以正常实现
>2 03 04
>3 05 06
>4 07 08
>5 09 10

 

posted @ 2022-02-03 00:21  小鲨鱼2018  阅读(209)  评论(0编辑  收藏  举报