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

2022/2/3 7:12:27

本文主要是介绍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

 



这篇关于linux中如何使用变量提取连续的行的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程