华域联盟 linux shell Linux shell 获得字符串所在行数及位置的方法

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Linux shell 获得字符串所在行数及位置的方法

转载请保留出处和原文链接:https://www.cnhackhy.com/19389.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部