String Manipulation in Shell Scripts: 3 Examples

Explore practical examples of string manipulation in shell scripts. Enhance your scripting skills with these clear, concise examples.
By Jamie

Introduction to String Manipulation in Shell Scripts

String manipulation is a crucial skill in shell scripting, allowing you to process and transform text data efficiently. This can be particularly useful when dealing with filenames, user input, or parsing output from commands. Below are three practical examples of string manipulation in shell scripts that demonstrate how to extract, modify, and format strings effectively.

Example 1: Extracting a Substring from a String

Context

In many cases, you may need to extract a specific part of a string, such as a filename or a specific identifier from a larger string. This example demonstrates how to achieve that using substring extraction.

#!/bin/bash

# Original string
input_string="This is a sample string."

# Extract a substring (from index 10 to 16)
substring=${input_string:10:6}

echo "Extracted substring: $substring"

Notes

  • The syntax ${string:start:length} is used to extract a substring from the given string.
  • Adjust the start and length values as needed to extract different sections.

Example 2: Replacing Substrings in a String

Context

Sometimes, you may need to replace specific substrings within a string, such as updating a configuration value or correcting a typo. This example illustrates how to perform substring replacement.

#!/bin/bash

# Original string
input_string="I love programming in Python."

# Replace 'Python' with 'Shell scripting'
modified_string=${input_string/Python/Shell scripting}

echo "Modified string: $modified_string"

Notes

  • The syntax ${string/old/new} replaces the first occurrence of old with new. To replace all occurrences, use ${string//old/new}.
  • This can be especially useful for dynamic configurations in scripts.

Example 3: Converting a String to Uppercase

Context

When processing strings, you may need to change the case for consistency, such as converting user input to uppercase. This example shows how to convert a string to uppercase in a shell script.

#!/bin/bash

# Original string
input_string="hello world"

# Convert to uppercase
uppercase_string=$(echo "$input_string" | tr '[:lower:]' '[:upper:]')

echo "Uppercase string: $uppercase_string"

Notes

  • The tr command is used here to translate lowercase letters to uppercase.
  • This method is efficient for transforming strings and ensuring uniformity in data processing.

By using these examples of string manipulation in shell scripts, you can enhance your scripting capabilities and streamline your workflows.