Linux shell 获得字符串所在行数及位置的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Linux shell 获得字符串所在行数及位置的方法

  2021-04-03 我要评论

01 获取字符串所在的行数

方式一:用grep -n

[root@root]# cat test
apple
bit
create
delect
exe
flow
good
[root@root]# cat test | grep -n exe
5:exe
[root@root]# cat test | grep -n exe | awk -F ":" '{print $1}'
5

方式二:用sed -n '/查询的字符串/=' 文件

[root@root]# cat test
apple
bit
create
delect
exe
flow
good
[root@root]# 
[root@root]# sed -n '/exe/=' test
5

02 获取字符串中字符所在的位置

方式一:用awk -F 和 wc -c 组合

[root@root]# echo 'uellevcmpottcap' | awk -F 'ott' '{print $1}';
uellevcmp
[root@root]# echo 'uellevcmpottcap' | awk -F 'ott' '{print $1}' | wc -c
10

方式二:用awk 'BEGIN{print index("'${str}'","'${str1}'") }'

[root@root]# str='uellevcmpottcap';str1='ott';awk 'BEGIN{print index("'${str}'","'${str1}'") }'
10
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们