Cao Yi

Extracting Substrings in Bash Shell Scripts

Index

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

Reference: https://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script

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:


This article has been rewritten using GPT-4. Source.