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 shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-02-03 c语言中求数组元素的最大值和最小值
2021-02-03 c语言中对象式宏(全局变量)
2021-02-03 c语言中实现数组的倒序排列
2021-02-03 linux系统 centos7.9 中安装 Rsudio-server