For a given string:
a="This is test.txt file"
How to find position of the .
in a shell environment? It should return 13
.
For a given string:
a="This is test.txt file"
How to find position of the .
in a shell environment? It should return 13
.
Using BASH:
a="This is test.txt file"
s="${a%%.*}" # remove all text after DOT and store in variable s
echo "$(( ${#s} + 1 ))" # get string length of $s + 1
13
Or using awk
:
awk -F. '{print length($1)+1}' <<< "$a"
13
Clearly this is a duplicated question but all answers are not on both pages.
Additional useful information can be found at Position of a string within a string using Linux shell script?
This script will find a single character or a multi-character string. I've modified the code on the other page to fit the question here:
#strindex.sh
A="This is test.txt file"
B=.
strindex() {
X="${1%%$2*}"
[[ "$X" = "$1" ]] && echo -1 || echo "$[ ${#X} + 1 ]"
}
strindex "$A" "$B"
#end
This returns 13 as requested.
In the above example I would prefer to define the variables 'A' and 'B' with A="$(cat $1)" and B="$2" so the script can be used on any file and any search string from the command line. Note I also changed the variables to upper case from the other page's example. This is not mandatory but some people think variables in upper case is a nice convention and easier to read and identify.