Linux shell String Operations (length, find, replace) detailed
The following two string operations are described in this blog post,
1 ${string:p osition} #在 $string, extract substring 2 ${string starting from position $position : Position:length}
View Code
The location of the character/substring in the parent string is required (position), and the shell string does not provide an interface for the location of the substring, and if the operation is based on a string variable, the location of the substring cannot be predicted;
Position of a string within a string using Linux shell script?
The article mentions some solutions that feel valuable and reproduced as follows:
If I has 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=catstrindex() { x="${1%%$2*}" [[ $x = $1 ]] && echo -1 || echo ${#x}}strindex "$a" "$b" # prints 4strindex "$a" foo # prints -1
ShareImprove this answer2.
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:
[[email protected] ~]$ echo "The cat sat on the mat" | grep -b -o cat4:cat
You can pipe this 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 this a="The cat sat on the mat"test="cat"awk -v a="$a" -v b="$test" ‘BEGIN{print index(a,b)}‘
|
Position character position in shell string to get character position