假定有一个名为test.txt的文件(后面的示例皆以该文件为例),内容如下:
1[root@root]# cat test.txt
2apple
3bit
4exe
5create
6delect
7exe
8flow
9good
Linux shell获得字符串所在行数及位置
方式一:用 grep -n
1[root@root]# cat test.txt | grep -n exe
23:exe
36:exe
4
5[root@root]# cat test.txt | grep -n exe | awk -F ":" '{print $1}'
63
76
方式二:用 sed -n /查询的字符串/= 文件
1[root@root]# sed -n '/exe/=' test.txt
23
36
linux 截取某行后面所有的行
在Linux中,可以使用sed命令来截取某行后面的所有行。示例如下:
截取第2行到第5行的内容
1[root@root]# sed -n '2,5p' test.txt
2bit
3exe
4create
5delect
说明:p表示输出。
截取第N(N>=1)行后面所有的行
截取第4行后面所有的行:
1[root@root]# sed -n '4,$p' test.txt
2create
3delect
4exe
5flow
6good
说明:
- -n选项是用来告诉sed默认不输出,只输出被模式匹配到的行。
- ‘4,$p’是一个模式,其中4,$表示从第4行到文件末尾的范围,p表示输出。
截取匹配到的字符串后面的所有行
命令:sed -n '/pattern/,$p' file
说明:/pattern/是你要匹配的模式,$p表示从匹配行到文件末尾的所有行。
示例:截取exe字符串后面所有的行
1[root@root]# sed -n '/exe/,$p' test.txt
2exe
3create
4delect
5exe
6flow
7good
评论