Basic String Operations

ShellShellBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn about fundamental string operations in shell scripting. String operations are essential for manipulating and extracting data from text in various scripting tasks. You will explore concepts such as determining string length, finding character positions, extracting substrings, and replacing parts of strings. These skills are crucial for effective text processing in shell scripts.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/VariableHandlingGroup -.-> shell/str_manipulation("`String Manipulation`") shell/VariableHandlingGroup -.-> shell/param_expansion("`Parameter Expansion`") shell/AdvancedScriptingConceptsGroup -.-> shell/cmd_substitution("`Command Substitution`") subgraph Lab Skills linux/touch -.-> lab-385386{{"`Basic String Operations`"}} shell/shebang -.-> lab-385386{{"`Basic String Operations`"}} shell/comments -.-> lab-385386{{"`Basic String Operations`"}} shell/quoting -.-> lab-385386{{"`Basic String Operations`"}} shell/variables_decl -.-> lab-385386{{"`Basic String Operations`"}} shell/variables_usage -.-> lab-385386{{"`Basic String Operations`"}} shell/str_manipulation -.-> lab-385386{{"`Basic String Operations`"}} shell/param_expansion -.-> lab-385386{{"`Basic String Operations`"}} shell/cmd_substitution -.-> lab-385386{{"`Basic String Operations`"}} end

Creating a Script File

Let's start by creating a script file where we'll write our string operations.

  1. Open your terminal in the WebIDE. The terminal is where you'll type commands to interact with the Linux system.

  2. Navigate to the project directory:

    cd ~/project

    This command changes your current directory to ~/project. The ~ symbol represents your home directory, so ~/project is a folder named "project" in your home directory.

  3. Create a new file named string_operations.sh:

    touch string_operations.sh

    The touch command creates a new, empty file. If the file already exists, it updates the file's timestamp.

  4. Open the file in the WebIDE editor. You can do this by clicking on the file name in the file explorer on the left side of your WebIDE.

  5. Add the following shebang line at the top of the file to specify the interpreter:

    #!/bin/bash

    This line, called a "shebang", tells the system to use the Bash shell to interpret this script. It's always the first line of a shell script.

String Length

Now, let's learn how to determine the length of a string.

  1. Add the following code to your string_operations.sh file:

    echo "Step 2: String Length"
    
    STRING="Hello, World!"
    LENGTH=${#STRING}
    
    echo "The string is: $STRING"
    echo "Its length is: $LENGTH"

    Let's break this down:

    • We define a variable STRING and assign it the value "Hello, World!".
    • ${#STRING} is a special syntax that calculates the length of the string stored in the STRING variable.
    • We store this length in the LENGTH variable.
    • Finally, we print out both the string and its length.
  2. Save the file. In most editors, you can do this by pressing Ctrl+S (or Cmd+S on Mac).

  3. Make the script executable:

    chmod +x string_operations.sh

    This command changes the permissions of the file to make it executable. chmod stands for "change mode", and +x means "add execute permission".

  4. Run the script:

    ./string_operations.sh

    The ./ tells the shell to look for the script in the current directory.

You should see output similar to:

Step 2: String Length
The string is: Hello, World!
Its length is: 13

If you don't see this output, double-check that you've saved the file and made it executable.

Finding Character Position

Next, we'll learn how to find the position of a character in a string.

  1. Add the following code to your string_operations.sh file:

    echo -e "\nStep 3: Finding Character Position"
    
    STRING="abcdefghijklmnopqrstuvwxyz"
    CHAR="j"
    
    POSITION=$(expr index "$STRING" "$CHAR")
    
    echo "The string is: $STRING"
    echo "We're looking for the character: $CHAR"
    echo "It is at position: $POSITION"

    Here's what this code does:

    • We define a STRING variable containing the alphabet.
    • We define a CHAR variable with the character we're looking for.
    • expr index "$STRING" "$CHAR" is a command that finds the position of $CHAR in $STRING.
    • We capture the output of this command in the POSITION variable using $().
    • Finally, we print out the results.
  2. Save the file and run the script again:

    ./string_operations.sh

You should see additional output similar to:

Step 3: Finding Character Position
The string is: abcdefghijklmnopqrstuvwxyz
We're looking for the character: j
It is at position: 10

Note that the position is 1-indexed, meaning the first character is at position 1, not 0.

Substring Extraction

Now, let's learn how to extract a portion of a string.

  1. Add the following code to your string_operations.sh file:

    echo -e "\nStep 4: Substring Extraction"
    
    STRING="The quick brown fox jumps over the lazy dog"
    START=10
    LENGTH=5
    
    SUBSTRING=${STRING:$START:$LENGTH}
    
    echo "The original string is: $STRING"
    echo "Extracting 5 characters starting from position 10:"
    echo "The substring is: $SUBSTRING"

    Let's break this down:

    • We define a STRING variable with a sample sentence.
    • START is the position where we want to start extracting (remember, it's 0-indexed here).
    • LENGTH is how many characters we want to extract.
    • ${STRING:$START:$LENGTH} is the syntax for extracting a substring. It means "from STRING, take LENGTH characters starting at position START".
    • We store this substring in the SUBSTRING variable and then print everything out.
  2. Save the file and run the script again:

    ./string_operations.sh

You should see additional output similar to:

Step 4: Substring Extraction
The original string is: The quick brown fox jumps over the lazy dog
Extracting 5 characters starting from position 10:
The substring is: brown

Note that unlike the expr index command, the string positions here start at 0, not 1. This is why we get "brown" starting from position 10.

String Replacement

Finally, let's learn how to replace parts of a string.

  1. Add the following code to your string_operations.sh file:

    echo -e "\nStep 5: String Replacement"
    
    STRING="The quick brown fox jumps over the lazy dog"
    echo "Original string: $STRING"
    
    ## Replace the first occurrence of 'o' with 'O'
    NEW_STRING=${STRING/o/O}
    echo "Replacing first 'o' with 'O': $NEW_STRING"
    
    ## Replace all occurrences of 'o' with 'O'
    NEW_STRING=${STRING//o/O}
    echo "Replacing all 'o' with 'O': $NEW_STRING"
    
    ## Replace 'quick' with 'slow' if it's at the beginning of the string
    NEW_STRING=${STRING/#quick/slow}
    echo "Replacing 'quick' with 'slow' at the beginning: $NEW_STRING"
    
    ## Replace 'dog' with 'cat' if it's at the end of the string
    NEW_STRING=${STRING/%dog/cat}
    echo "Replacing 'dog' with 'cat' at the end: $NEW_STRING"

    This code demonstrates various string replacement techniques:

    • ${STRING/o/O} replaces the first occurrence of 'o' with 'O'.
    • ${STRING//o/O} replaces all occurrences of 'o' with 'O'.
    • ${STRING/#quick/slow} replaces 'quick' with 'slow', but only if 'quick' is at the beginning of the string.
    • ${STRING/%dog/cat} replaces 'dog' with 'cat', but only if 'dog' is at the end of the string.
  2. Save the file and run the script one last time:

    ./string_operations.sh

You should see additional output similar to:

Step 5: String Replacement
Original string: The quick brown fox jumps over the lazy dog
Replacing first 'o' with 'O': The quick brOwn fox jumps over the lazy dog
Replacing all 'o' with 'O': The quick brOwn fOx jumps Over the lazy dOg
Replacing 'quick' with 'slow' at the beginning: The quick brown fox jumps over the lazy dog
Replacing 'dog' with 'cat' at the end: The quick brown fox jumps over the lazy cat

Notice how each replacement operation affects the string differently.

Summary

In this lab, you have learned and practiced several fundamental string operations in shell scripting:

  1. Creating and executing a shell script
  2. Calculating the length of a string
  3. Finding the position of a character in a string
  4. Extracting a substring from a larger string
  5. Performing various string replacement operations

These skills form the foundation for more complex text processing tasks in shell scripting. As you continue to work with shell scripts, you'll find these string operations invaluable for manipulating and analyzing text data in your projects. Remember, practice is key to mastering these concepts, so don't hesitate to experiment with different strings and operations!

Other Shell Tutorials you may like