Obtain the original string: ${var_name}
.
$ a='abc123'
$ echo $a
abc123
Modify a section of ${var_name}
:
Remove all digit characters and replace them with an empty string
$ echo ${a//[0-9]/}
abc
Remove all non-digit characters and replace them with an empty string
$ echo ${a//[!0-9]/}
123
Replace digits with ‘dd’
$ echo ${a//[0-9]/dd}
abcdddddd
Another example. Extract digits at the end of a string. Assisted by ChatGPT.
Question: Can you please explain the following commands and outputs?
$ b='a2b23c234'
$ echo $b
a2b23c234
$ echo ${b##*[!0-9]}
234
Answer:
The first command assigns the variable b
the value a2b23c234
The second command, echo $b
, displays the value of the variable b
: a2b23c234
The third command, echo ${b##*[!0-9]}
, displays the numeric characters at the end of the variable b
, which is 234
Explanation of the third command:
${b##*[!0-9]}
is a parameter expansion that removes the longest substring matching the pattern *[!0-9]
from the beginning of the variable b
.*[!0-9]
matches any sequence of characters that does not end with a numeric digit.This article has been rewritten using GPT-4. Source.