Bash string manipulation
abbazs
Posted on July 1, 2024
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
pattern
from the beginning ofvariable
.
- Removes the shortest match of
x="abc.def.ghi"
echo ${x#*.} # Outputs: def.ghi
-
${variable##pattern}
:- Removes the longest match of
pattern
from the beginning ofvariable
.
- Removes the longest match of
x="abc.def.ghi"
echo ${x##*.} # Outputs: ghi
-
${variable%pattern}
:- Removes the shortest match of
pattern
from the end ofvariable
.
- Removes the shortest match of
x="abc.def.ghi"
echo ${x%.*} # Outputs: abc.def
-
${variable%%pattern}
:- Removes the longest match of
pattern
from the end ofvariable
.
- Removes the longest match of
x="abc.def.ghi"
echo ${x%%.*} # Outputs: abc
-
${variable:offset:length}
:- Extracts a substring from
variable
starting atoffset
and of lengthlength
.
- Extracts a substring from
x="abc.def.ghi"
echo ${x:4:3} # Outputs: def
-
${variable/pattern/replacement}
:- Replaces the first match of
pattern
withreplacement
invariable
.
- Replaces the first match of
x="abc.def.ghi"
echo ${x/def/xyz} # Outputs: abc.xyz.ghi
-
${variable//pattern/replacement}
:- Replaces all matches of
pattern
withreplacement
invariable
.
- 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.
💖 💪 🙅 🚩
abbazs
Posted on July 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.