Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position of a string within a string using Linux shell script?

Tags:

linux

shell

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?

like image 742
yazz.com Avatar asked Feb 17 '11 16:02

yazz.com


People also ask

How do I find a character in a string in Unix?

Using Grep The grep command can also be used to find strings in another string. In the following example, we are passing the string $STR as an input to grep and checking if the string $SUB is found within the input string. The command will return true or false as appropriate.

How do you check if a substring is present in a string in shell script?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.

How do you find the position of a character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.


1 Answers

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 
like image 165
glenn jackman Avatar answered Sep 19 '22 13:09

glenn jackman