0
0
Bash Scriptingscripting~5 mins

Why string manipulation is frequent in Bash Scripting

Choose your learning style9 modes available
Introduction
String manipulation is common because many tasks involve working with text data like filenames, user input, or command output. Changing or extracting parts of text helps automate and simplify these tasks.
Renaming multiple files by changing parts of their names.
Extracting specific information from a text file or command output.
Validating or formatting user input in scripts.
Combining or splitting text to create reports or logs.
Cleaning up data by removing unwanted characters or spaces.
Syntax
Bash Scripting
var="Hello World"
# Extract substring: ${var:6:5}
# Replace substring: ${var/World/Bash}
# Length of string: ${#var}
Use ${var:start:length} to get part of a string.
Use ${var/old/new} to replace first occurrence of 'old' with 'new'.
Examples
Extracts 'World' from the string.
Bash Scripting
text="Hello World"
echo ${text:6:5}
Replaces 'World' with 'Bash' in the string.
Bash Scripting
text="Hello World"
echo ${text/World/Bash}
Prints the length of the string, which is 11.
Bash Scripting
text="Hello World"
echo ${#text}
Sample Program
This script extracts the year '2024' from the filename and replaces underscores with spaces for a nicer display.
Bash Scripting
#!/bin/bash
input="file_2024_report.txt"
# Extract year from filename
year=${input:5:4}
# Replace underscores with spaces
newname=${input//_/ }
echo "Year extracted: $year"
echo "New filename: $newname"
OutputSuccess
Important Notes
Double slashes in ${var//old/new} replace all occurrences, not just the first.
Be careful with indexes; counting starts at 0.
Quotes around variables help prevent word splitting and globbing.
Summary
String manipulation helps handle text data in scripts.
Common operations include extracting, replacing, and measuring strings.
Bash provides simple syntax to do these tasks efficiently.