shell 字符串中定位字符位置 獲取字符位置


linux shell 字符串操作(長度,查找,替換)詳解

該博文中描述的如下兩個字符串操作,

1 ${string:position}     #在$string中, 從位置$position開始提取子串
2 ${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
share improve 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

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)}'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM