Ask Your Question
3

In POSIX sh, what is the method to detect the presence of one string within another?

asked 2022-03-06 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-09-05 16:00:00 +0000

plato gravatar image

The method to detect the presence of one string within another in POSIX sh is to use parameter expansion, specifically the ${parameter#word} and ${parameter##word} forms.

To check if a string "substring" is contained within another string "string":

if [ "${string#*$substring*}" != "$string" ]; then
    echo "substring is present in string"
fi

Explanation:

${string#*$substring*} removes the substring and everything before it from the variable string. If the substring is not present, it returns the original value of string.

If the resulting value is not equal to the original string value, then that means the substring was found and the condition is true.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-06 11:00:00 +0000

Seen: 10 times

Last updated: Sep 05 '21