String Manipulation Techniques

ShellBeginner
Practice Now

Introduction

When writing scripts, you often need to modify text stored in variables. You might need to extract a specific part of a file path, replace a word in a configuration setting, or ensure a variable has a valid value even if the user didn't provide one.

Bash provides powerful built-in tools for these tasks called parameter expansion.

This is an important shell concept because it lets you transform text without launching extra commands. In shell scripting, using built-in features is often faster and simpler than calling external utilities for every small change.

In this lab, you will learn three essential string manipulation techniques:

  1. Slicing: Extracting a specific portion of a string (e.g., the first 5 characters).
  2. Replacement: Finding and replacing text within a string.
  3. Default Values: Automatically assigning a backup value if a variable is missing or empty.

Define a String Variable

Let's start by creating a variable containing a long file path. We will use this string to practice our manipulation techniques.

String handling appears everywhere in shell work because so much system information is represented as text: paths, usernames, hostnames, configuration values, and command output. Learning to reshape text without leaving the shell is a major productivity gain.

Create a new script named string_lab.sh.

Open string_lab.sh and add the following code:

nano string_lab.sh
#!/bin/bash

## Define a variable with a file path
FILE_PATH="/usr/local/share/applications/config.xml"

echo "Original Path: $FILE_PATH"

Save (Ctrl+O, Enter) and Exit (Ctrl+X).

Make it executable and run it to prepare the environment:

chmod +x string_lab.sh
./string_lab.sh

You should see the full path printed out. Now, let's start manipulating this string.

Extract a Substring (Slicing)

Sometimes you only want a specific part of a string, such as the first few characters. This is called Slicing.

The syntax for slicing is: ${Variable:Offset:Length}

  • Offset: Where to start (0 is the first character).
  • Length: How many characters to take.

This is done with parameter expansion, which means Bash transforms the variable value internally before running the command. No extra utility such as cut is needed for a simple substring operation.

We want to extract the first 5 characters (/usr/) from our FILE_PATH.

Open string_lab.sh:

nano string_lab.sh

Add the following code at the bottom:

## Slicing: Start at index 0, take 5 characters
## Syntax: ${Variable : Start : Length}
SLICE=${FILE_PATH:0:5}

echo "First 5 characters: $SLICE"

Save and Exit. Run it:

./string_lab.sh

Result:

First 5 characters: /usr/

Bash extracted exactly 5 characters starting from the beginning of the string.

Replace a Substring

This technique works like "Find and Replace" in a text editor.

The syntax is: ${Variable/Find/Replace}.

Let's say we want to change the folder share to bin in our file path.

Open string_lab.sh:

nano string_lab.sh

Add this code:

## Replacement: Find 'share', replace with 'bin'
## Syntax: ${Variable / Pattern / Replacement}
NEW_PATH=${FILE_PATH/share/bin}

echo "Modified Path: $NEW_PATH"

Save and Exit. Run it:

./string_lab.sh

Result:

Modified Path: /usr/local/bin/applications/config.xml

The shell found the first occurrence of share and replaced it with bin.

This is often useful for path manipulation, filename cleanup, and quick configuration changes. Because the work happens inside Bash itself, it is usually lighter and easier to read than launching a separate text-processing command for a small substitution.

Provide a Default Value

Scripts often rely on inputs or environment variables (like USER or HOME). If these variables are missing, your script might crash or behave unpredictably.

You can provide a Default Value to be used if the variable is unset or empty.

The syntax is: ${Variable:-DefaultValue}.

Open string_lab.sh:

nano string_lab.sh

Add this code. Note that USER_NAME has not been defined in our script, so it is currently unset.

## Default Value: If USER_NAME is missing, use 'guest'
## Syntax: ${Variable :- Default}
CURRENT_USER=${USER_NAME:-guest}

echo "Current User: $CURRENT_USER"

Save and Exit. Run it:

./string_lab.sh

Result:

Current User: guest

Because USER_NAME was not defined, Bash dealt with the missing data by using the fallback value guest. This ensures your script continues running smoothly.

This pattern is especially helpful in automation, where input may come from environment variables or optional arguments. A sensible default can make a script safer and more predictable when some data is missing.

Summary

In this lab, you learned how to manipulate strings directly within Bash using Parameter Expansion:

  1. Slicing (${var:offset:length}): Extracting precise substrings.
  2. Replacing (${var/old/new}): modifying the content of a variable.
  3. Default Values (${var:-default}): Handling missing variables gracefully.

These techniques allow you to write robust scripts that can handle text processing efficiently without needing external tools like sed or awk for simple tasks.