0

For a given string:

a="This is test.txt file"

How to find position of the . in a shell environment? It should return 13.

Ankit Sharma
  • 3,923
  • 2
  • 29
  • 49
Mitko Gurbanski
  • 105
  • 2
  • 4
  • 12

2 Answers2

4

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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.

unifex
  • 165
  • 1
  • 6