DEV Community

abbazs
abbazs

Posted on

Bash string manipulation

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 of variable.
   x="abc.def.ghi"
   echo ${x#*.}  # Outputs: def.ghi
Enter fullscreen mode Exit fullscreen mode
  • ${variable##pattern}:
    • Removes the longest match of pattern from the beginning of variable.
   x="abc.def.ghi"
   echo ${x##*.}  # Outputs: ghi
Enter fullscreen mode Exit fullscreen mode
  • ${variable%pattern}:
    • Removes the shortest match of pattern from the end of variable.
   x="abc.def.ghi"
   echo ${x%.*}  # Outputs: abc.def
Enter fullscreen mode Exit fullscreen mode
  • ${variable%%pattern}:
    • Removes the longest match of pattern from the end of variable.
   x="abc.def.ghi"
   echo ${x%%.*}  # Outputs: abc
Enter fullscreen mode Exit fullscreen mode
  • ${variable:offset:length}:
    • Extracts a substring from variable starting at offset and of length length.
   x="abc.def.ghi"
   echo ${x:4:3}  # Outputs: def
Enter fullscreen mode Exit fullscreen mode
  • ${variable/pattern/replacement}:
    • Replaces the first match of pattern with replacement in variable.
   x="abc.def.ghi"
   echo ${x/def/xyz}  # Outputs: abc.xyz.ghi
Enter fullscreen mode Exit fullscreen mode
  • ${variable//pattern/replacement}:
    • Replaces all matches of pattern with replacement in variable.
   x="abc.def.ghi"
   echo ${x//./-}  # Outputs: abc-def-ghi
Enter fullscreen mode Exit fullscreen mode
  • ${variable^pattern}:
    • Converts the first character to uppercase (bash 4.0 and above).
   x="abc"
   echo ${x^}  # Outputs: Abc
Enter fullscreen mode Exit fullscreen mode
  • ${variable^^pattern}:
    • Converts all characters to uppercase (bash 4.0 and above).
   x="abc"
   echo ${x^^}  # Outputs: ABC
Enter fullscreen mode Exit fullscreen mode
  • ${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)