Web Analytics

String Manipulation

Intermediate ~20 min read

Bash provides powerful built-in capabilities for manipulating strings without needing external tools like sed or awk for simple tasks. In this lesson, we'll explore how to extract substrings, replace text patterns, and change string case directly within Bash.

Substring Extraction

You can extract a portion of a string using the syntax ${string:position:length}.

  • position: The starting index (0-based).
  • length: (Optional) The number of characters to extract. If omitted, extracts to the end of the string.

String Replacement

Bash allows you to replace patterns within a string using ${string/pattern/replacement}.

  • ${string/pattern/replacement}: Replaces the first occurrence.
  • ${string//pattern/replacement}: Replaces all occurrences.

Case Conversion

Starting from Bash 4.0, you can easily convert case using ^ (uppercase) and , (lowercase).

  • ${var^^}: Converts all characters to uppercase.
  • ${var,,}: Converts all characters to lowercase.
Output
Click Run to execute your code
Tip: These operations are pure Bash features. They are faster than spawning external processes like sed or cut because they run inside the shell process itself.

Summary

  • Use ${var:start:len} for substrings.
  • Use ${var/old/new} for single replacement.
  • Use ${var//old/new} for global replacement.
  • Use ${var^^} and ${var,,} for case conversion.

What's Next?

Next, we'll dive deeper into one of Bash's most powerful features: Parameter Expansion, which allows for even more complex string operations.