Can the 'expr index' command only find the position of a single character in a string?

QuestionsQuestions8 SkillsProBasic String OperationsAug, 26 2025
0179

The expr index command is designed to find the position of the first occurrence of a single character in a string. If you want to find the positions of multiple characters or substrings, you would need to use a different approach, such as iterating through the string with a loop or using other string manipulation commands.

For example, to find multiple characters, you could use a loop in a script:

STRING="hello world"
CHARACTERS="lo"

for CHAR in $(echo $CHARACTERS | fold -w1); do
    POSITION=$(expr index "$STRING" "$CHAR")
    echo "Character '$CHAR' found at position: $POSITION"
done

This script will find the position of each character in the CHARACTERS variable within the STRING.

0 Comments

no data
Be the first to share your comment!