shell 字符串中定位字符位置 获取字符位置
2016-01-01 09:12
776 查看
linux shell 字符串操作(长度,查找,替换)详解
该博文中描述的如下两个字符串操作,
View Code
需要用到字符/子串在父字符串中的位置(position);而shell字符串并未提供获取子串所在位置的接口,如果基于字符串变量的操作,则无法预知子串的位置;
If I have the text in a shell variable, say
How can I search for "cat" and return 4 using a Linux shell script, or -1 if not found?
1、
With bash
shareimprove this answer
2、
I used awk for this
3、
4、
You can use grep to get the byte-offset of the matching part of a string:
As per your example:
you can pipe that to awk if you just want the first part
该博文中描述的如下两个字符串操作,
${string:position} #在$string中, 从位置$position开始提取子串 ${string:position:length} #在$string中, 从位置$position开始提取长度为$length的子串
View Code
需要用到字符/子串在父字符串中的位置(position);而shell字符串并未提供获取子串所在位置的接口,如果基于字符串变量的操作,则无法预知子串的位置;
Position of a string within a string using Linux shell script?
该文提到了一些解决方案,觉得有价值,转载如下:If I have the text in a shell variable, say
$a:
a="The cat sat on the mat"
How can I search for "cat" and return 4 using a Linux shell script, or -1 if not found?
1、
With bash
a="The cat sat on the mat"b=cat
strindex() {
x="${1%%$2*}"
[[ $x = $1 ]] && echo -1 || echo ${#x}
}
strindex "$a" "$b" # prints 4
strindex "$a" foo # prints -1
shareimprove this answer
2、
I used awk for this
a="The cat sat on the mat"test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
3、
echo $a | grep -bo cat | sed 's/:.*$//'
4、
You can use grep to get the byte-offset of the matching part of a string:
echo $str | grep -b -o str
As per your example:
[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat 4:cat
you can pipe that to awk if you just want the first part
echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}' echo $str | grep -b -o "cat" | cut -d: -f1
5 down vote | I used awk for thisa="The cat sat on the mat"test="cat" |
相关文章推荐
- -bash: grunt-cli: command not found
- -bash: fork: retry: Resource temporarily unavailable
- shell如何取到文件中某一行某一列的内容
- shell脚本编程<二>:if-then,case结构化命令
- shell修改配置文件
- shell脚本编程<一>:变量及脚本中数学计算
- bash反弹shell
- 基于CentOS的MySQL学习补充五--使用Shell备份(mysqldump)MySQL数据库
- mysqldump全备的shell脚本分享
- 一个备份MySQL数据库的简单Shell脚本
- linux shell 脚本30分钟教程
- ShellExcuteA
- linux创建新用户后shell无法自动补全命令
- 程序中执行shell命令行,获取system目录读写权限
- linux shell 输入密码不显示
- linuxSHELL学习之数字比较、字符串比较
- linux shell 正则表达式(BREs,EREs,PREs)差异比较(转)
- shell数组建立和基本使用方法
- bash脚本编程之一变量、变量类型等
- shell中的变量的备忘