In bash, there are several string manipulation operations that can be used to remove parts of a string based on patterns. Here are some of the most commonly used ones
-
${variable#pattern}:- Removes the shortest match of
patternfrom the beginning ofvariable.
- Removes the shortest match of
x="abc.def.ghi"
echo ${x#*.} # Outputs: def.ghi
-
${variable##pattern}:- Removes the longest match of
patternfrom the beginning ofvariable.
- Removes the longest match of
x="abc.def.ghi"
echo ${x##*.} # Outputs: ghi
-
${variable%pattern}:- Removes the shortest match of
patternfrom the end ofvariable.
- Removes the shortest match of
x="abc.def.ghi"
echo ${x%.*} # Outputs: abc.def
-
${variable%%pattern}:- Removes the longest match of
patternfrom the end ofvariable.
- Removes the longest match of
x="abc.def.ghi"
echo ${x%%.*} # Outputs: abc
-
${variable:offset:length}:- Extracts a substring from
variablestarting atoffsetand of lengthlength.
- Extracts a substring from
x="abc.def.ghi"
echo ${x:4:3} # Outputs: def
-
${variable/pattern/replacement}:- Replaces the first match of
patternwithreplacementinvariable.
- Replaces the first match of
x="abc.def.ghi"
echo ${x/def/xyz} # Outputs: abc.xyz.ghi
-
${variable//pattern/replacement}:- Replaces all matches of
patternwithreplacementinvariable.
- Replaces all matches of
x="abc.def.ghi"
echo ${x//./-} # Outputs: abc-def-ghi
-
${variable^pattern}:- Converts the first character to uppercase (bash 4.0 and above).
x="abc"
echo ${x^} # Outputs: Abc
-
${variable^^pattern}:- Converts all characters to uppercase (bash 4.0 and above).
x="abc"
echo ${x^^} # Outputs: ABC
-
${variable,pattern}:- Converts the first character to lowercase (bash 4.0 and above).
x="ABC" echo ${x,} # Outputs: aBC -
${variable,,pattern}:- Converts all characters to lowercase (bash 4.0 and above).
x="ABC" echo ${x,,} # Outputs: abc
These operations provide a powerful and flexible way to manipulate strings directly within bash scripts, allowing for efficient and concise code.
Top comments (0)