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中如何使用变量提取连续的行的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04Linux系统上离线升级SSH服务的具体操作步骤-icode9专业技术文章分享
- 2024-06-0600-macOS和Linux安装和管理多个Python版本
- 2024-03-30[译]漫画SELinux概念
- 2024-03-29linux 移动文件
- 2024-03-28linux .so file
- 2024-03-28Linux 磁盘管理
- 2024-03-28Linux学习笔记(十三)磁盘管理(一):磁盘分区
- 2024-03-26linux 创建 文件
- 2024-03-25使用SecureCRT对Linux vim进行颜色设置
- 2024-03-202019-2020-12 20199317 《Linux内核原理与分析》 第十二周作业