How can I extract the content following a specific string in the shell?

We can use string manipulation in a shell script to extract the content after a specific string. The specific method is as follows:

  1. Use the “#” character to delete the content in front of the string.
str="Hello World"
result="${str#*o}"
echo $result  # 输出: World

In the code above, ${str#*o} removes the first occurrence of the character “o” and all characters before it in the string.

  1. Use the “##” character to remove the content before the string (greedy matching):
str="Hello World"
result="${str##*o}"
echo $result  # 输出: rld

In the above code, ${str##*o} means deleting the last occurrence of the character “o” and its preceding content from the string.

Please choose the appropriate method of string truncation based on specific needs.

广告
Closing in 10 seconds
bannerAds