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.
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"
${string:start:length}
is used to extract a substring from the given string.start
and length
values as needed to extract different sections.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"
${string/old/new}
replaces the first occurrence of old
with new
. To replace all occurrences, use ${string//old/new}
.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"
tr
command is used here to translate lowercase letters to uppercase.By using these examples of string manipulation in shell scripts, you can enhance your scripting capabilities and streamline your workflows.