Can the position of a character in a string be found using other methods in bash?

QuestionsQuestions8 SkillsProBasic String OperationsDec, 03 2025
074

Yes, you can find the position of a character in a string using various methods in bash. Here are a couple of examples:

Using expr Command

You can use the expr command to find the position of a character:

string="Hello World"
char="o"
position=$(expr index "$string" "$char")
echo "The position of '$char' is: $position"

Using awk

You can also use awk to find the position of a character:

string="Hello World"
char="o"
echo "$string" | awk -v c="$char" '{for(i=1;i<=length($0);i++) if(substr($0,i,1)==c) print i}'

Using grep

Another method is to use grep with -o and -b options:

string="Hello World"
char="o"
echo "$string" | grep -b -o "$char" | cut -d: -f1

These methods will help you find the position of a character in a string in bash.

0 Comments

no data
Be the first to share your comment!