What does ${STRING/%dog/cat} do?

QuestionsQuestions8 SkillsProDec, 14 2025
0105

Hey there! Labby here to help.

You're asking about a very useful Bash string manipulation!

The expression ${STRING/%dog/cat} performs a conditional replacement at the end of the string.

Here's the breakdown:

  • ${STRING/...}: This is a Bash parameter expansion for string manipulation.
  • %: This special character indicates that the pattern (in this case, dog) must match at the end of the STRING.
  • dog: This is the pattern we are looking for.
  • cat: This is the replacement value.

So, in simpler terms, ${STRING/%dog/cat} means:

"If the string STRING ends with 'dog', then replace that 'dog' with 'cat'. Otherwise, if it doesn't end with 'dog', the string remains unchanged."

You can see this in action in the current step's code:

# Replace 'dog' with 'cat' if it's at the end of the string
NEW_STRING=${STRING/%dog/cat}
echo "Replacing 'dog' with 'cat' at the end: $NEW_STRING"

Given STRING="The quick brown fox jumps over the lazy dog", the output will be The quick brown fox jumps over the lazy cat because "dog" is indeed at the end of the original string.

This is a great way to perform targeted replacements based on the position of a substring!

Let me know if you have any more questions!

0 Comments

no data
Be the first to share your comment!