w3resource

Bash Text Substitution and Manipulation Exercises, Solution, Explanation

1.

Replace a word:

Write a Bash script that replaces all occurrences of a word with another word in a text file named "temp.txt".

Code:

#!/bin/bash

# Check if the number of arguments is not equal to 2
if [ $# -ne 2 ]; then
    echo "Usage: $0 <old_word> <new_word>"
    exit 1
fi

# Store old and new words in variables
old_word="$1"
new_word="$2"

# Replace all occurrences of old word with new word in temp.txt
sed -i "s/$old_word/$new_word/g" temp.txt

echo "All occurrences of '$old_word' replaced with '$new_word' in 'temp.txt'."

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.

This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh 5.2 5.200
All occurrences of '5.2' replaced with '5.200' in 'temp.txt'.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.200, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.

This is Edition 5.200, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.200.

Explanation:

In the exercise above,

  • $#: Represents the number of arguments passed to the script.
  • -ne: Checks if it is not equal to 2.
  • If the number of arguments is not 2, it prints a usage message showing how to use the script and exits with an error code (exit 1).
  • $1 and $2: These are the first and second arguments passed to the script.
  • They are stored in variables 'old_word' and 'new_word' respectively.
  • sed -i: Invokes the "sed" command for in-place editing of the file.
  • "s/$old_word/$new_word/g": This is the substitution command for "sed".
    • s: Indicates a substitution.
    • $old_word: The word to be replaced.
    • $new_word: The word to replace with.
    • g: Replaces all occurrences of the word in each line (global substitution).
  • temp.txt: The name of the file where the replacement is done.
  • Finally print a message indicating the successful replacement, mentioning the old and new words, and the file where the replacement took place.

2.

Uppercase conversion:

Write a Bash script that converts all text in a file named "temp.txt" to uppercase.

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Convert text in "temp.txt" to uppercase and save the result to a temporary file
awk '{print toupper($0)}' temp.txt > temp_uppercase.txt

# Replace the original file with the temporary file
mv temp_uppercase.txt temp.txt

# Check if the conversion was successful
if [ $? -eq 0 ]; then
    echo "Text in 'temp.txt' converted to uppercase successfully."
else
    echo "Failed to convert text in 'temp.txt' to uppercase."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.200, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.

This is Edition 5.200, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.200.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Text in 'temp.txt' converted to uppercase successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
THIS TEXT IS A BRIEF DESCRIPTION OF THE FEATURES THAT ARE PRESENT IN THE BASH SHELL (VERSION 5.200, 19 SEPTEMBER 2022). THE BASH HOME PAGE IS HTTP://WWW.GNU.ORG/SOFTWARE/BASH/.

THIS IS EDITION 5.200, LAST UPDATED 19 SEPTEMBER 2022, OF THE GNU BASH REFERENCE MANUAL, FOR BASH, VERSION 5.200.

Explanation:

In the exercise above,

  • Check File Existence:
    • Check if the file "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Convert to Uppercase:
    • Uses awk to convert each line of text in "temp.txt" to uppercase using the toupper function.
    • The output is redirected to a temporary file named "temp_uppercase.txt".
  • Replace Original File:
    • Replace the original "temp.txt" with the temporary file "temp_uppercase.txt".
  • Check Success:
    • Check if the conversion was successful by examining the exit status.
    • If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

3.

Lowercase conversion:

Write a Bash script that converts all text in a file named "temp.txt" to lowercase.

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Convert text in "temp.txt" to lowercase and save the result to a temporary file
awk '{print tolower($0)}' temp.txt > temp_lowercase.txt

# Replace the original file with the temporary file
mv temp_lowercase.txt temp.txt

# Check if the conversion was successful
if [ $? -eq 0 ]; then
    echo "Text in 'temp.txt' converted to lowercase successfully."
else
    echo "Failed to convert text in 'temp.txt' to lowercase."
fi 

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
THIS TEXT IS A BRIEF DESCRIPTION OF THE FEATURES THAT ARE PRESENT IN THE BASH SHELL (VERSION 5.200, 19 SEPTEMBER 2022). THE BASH HOME PAGE IS HTTP://WWW.GNU.ORG/SOFTWARE/BASH/.

THIS IS EDITION 5.200, LAST UPDATED 19 SEPTEMBER 2022, OF THE GNU BASH REFERENCE MANUAL, FOR BASH, VERSION 5.200.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Text in 'temp.txt' converted to lowercase successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
this text is a brief description of the features that are present in the bash shell (version 5.200, 19 september 2022). the bash home page is http://www.gnu.org/software/bash/.

this is edition 5.200, last updated 19 september 2022, of the gnu bash reference manual, for bash, version 5.200.

Explanation:

In the exercise above,

  • Check File Existence:
    • Check if the file "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Convert to Lowercase:
    • Uses "awk" to convert each line of text in "temp.txt" to lowercase using the "tolower()" function.
    • The output is redirected to a temporary file named "temp_lowercase.txt".
  • Replace Original File:
    • Replace the original "temp.txt" with the temporary file "temp_lowercase.txt".
  • Check Success:
    • Check if the conversion was successful by examining the exit status.
    • If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

4.

Reverse lines:

Write a Bash script that reverses the lines in a text file named "temp.txt".

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Reverse the lines in "temp.txt" and save the result to a temporary file
tac temp.txt > temp_reversed.txt

# Replace the original file with the reversed content
mv temp_reversed.txt temp.txt

# Check if the reversal was successful
if [ $? -eq 0 ]; then
    echo "Lines in 'temp.txt' reversed successfully."
else
    echo "Failed to reverse lines in 'temp.txt'."
fi 

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
this text is a brief description of the features that are present in the bash shell (version 5.200, 19 september 2022). the bash home page is http://www.gnu.org/software/bash/.

this is edition 5.200, last updated 19 september 2022, of the gnu bash reference manual, for bash, version 5.200.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Lines in 'temp.txt' reversed successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
this is edition 5.200, last updated 19 september 2022, of the gnu bash reference manual, for bash, version 5.200.

this text is a brief description of the features that are present in the bash shell (version 5.200, 19 september 2022). the bash home page is http://www.gnu.org/software/bash/.

Explanation:

In the exercise above,

  • Check File Existence:
    • Check if "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Reverse Lines:
    • Uses "tac" (reverse of "cat") to reverse the lines in "temp.txt".
    • The output is redirected to a temporary file named "temp_reversed.txt".
  • Replace Original File:
    • Replace the original "temp.txt" with the reversed content.
  • Check Success:
    • Check if the reversal was successful by examining the exit status.
    • If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

5.

Reverse characters:

Write a Bash script that reverses the characters in each line of a text file named "temp.txt".

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Reverse characters in each line of "temp.txt" and save the result to a temporary file
while IFS= read -r line; do
    echo "$line" | rev
done < temp.txt > temp_reversed.txt

# Replace the original file with the reversed content
mv temp_reversed.txt temp.txt

# Check if the reversal was successful
if [ $? -eq 0 ]; then
    echo "Characters in each line of 'temp.txt' reversed successfully."
else
    echo "Failed to reverse characters in each line of 'temp.txt'."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
this is edition 5.200, last updated 19 september 2022, of the gnu bash reference manual, for bash, version 5.200.

this text is a brief description of the features that are present in the bash shell (version 5.200, 19 september 2022). the bash home page is http://www.gnu.org/software/bash/.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Characters in each line of 'temp.txt' reversed successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
.002.5 noisrev ,hsab rof ,launam ecnerefer hsab ung eht fo ,2202 rebmetpes 91 detadpu tsal ,002.5 noitide si siht

./hsab/erawtfos/gro.ung.www//:ptth si egap emoh hsab eht .)2202 rebmetpes 91 ,002.5 noisrev( llehs hsab eht ni tneserp era taht serutaef eht fo noitpircsed feirb a si txet siht

Explanation:

In the exercise above,

  • Check file existence:
    • Check if the file "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Reverse Characters in Each Line:
    • Use a while loop to read each line of "temp.txt" and reverse it using the rev command.
    • The reversed line is then written to a temporary file named "temp_reversed.txt".
  • Replace the Original File:
    • Replace the original "temp.txt" with the reversed content.
  • Check for Success:
    • Check if the reversal was successful by examining the exit status.
    • o If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

6.

Remove empty lines:

Write a Bash script that removes empty lines from a text file named "file.txt".

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Remove empty lines from the text file "temp.txt" and save the result to a temporary file
grep -v '^$' temp.txt > temp_no_empty_lines.txt

# Replace the original file with the one without empty lines
mv temp_no_empty_lines.txt temp.txt

# Check if empty lines were successfully removed
if [ $? -eq 0 ]; then
    echo "Empty lines removed from 'temp.txt' successfully."
else
    echo "Failed to remove empty lines from 'temp.txt'."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.

This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Empty lines removed from 'temp.txt' successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.
This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.

Explanation:

In the exercise above,

  • Check file existence:
    • Check if the file "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Remove empty lines:
    • Use grep with the -v option to remove lines that match the pattern for an empty line (^$).
    • The result is saved to a temporary file named "temp_no_empty_lines.txt".
  • Replace the Original File:
    • Replace the original "temp.txt" with the one without empty lines.
  • Check for Success:
    • Check if the removal of empty lines was successful by examining the exit status.
    • If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

7.

Trim leading and trailing whitespace:

Write a Bash script that trims leading and trailing whitespace from each line in a text file named "data.txt".

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Trim leading and trailing whitespace from each line and save the result to a temporary file
awk '{$1=$1};1' temp.txt > temp_trimmed.txt

# Replace the original file with the trimmed one
mv temp_trimmed.txt temp.txt

# Check if whitespace was successfully trimmed
if [ $? -eq 0 ]; then
    echo "Whitespace trimmed from each line in 'temp.txt' successfully."
else
    echo "Failed to trim whitespace from 'temp.txt'."
fi 

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
     This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The    Bash    home page is http://www.gnu.org/software/bash/.

This    is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Whitespace trimmed from each line in 'temp.txt' successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.

This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.

Explanation:

In the exercise above,

  • Check file existence:
    • Check if the file "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Trim whitespace:
    • Use AWG to trim leading and trailing whitespace from each line.
    • The awk '{$1=$1};1' command reassigns each line to itself, which effectively trims the whitespace.
  • Replace the Original File:
    • Replace the original "temp.txt" with the trimmed version.
  • Check for Success:
    • Checks if whitespace trimming was successful by examining the exit status.
    • If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

8.

Insert text at beginning of each line:

Write a Bash script that inserts text at the beginning of each line in a text file named "file.txt".

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Text to insert at the beginning of each line
insert_text="New Text - "

# Use sed to insert text at the beginning of each line and save the result to a temporary file
sed "s/^/$insert_text/" temp.txt > temp_with_insert.txt

# Replace the original file with the one containing the inserted text
mv temp_with_insert.txt temp.txt

# Check if insertion was successful
if [ $? -eq 0 ]; then
    echo "Text inserted at the beginning of each line in 'temp.txt' successfully."
else
    echo "Failed to insert text at the beginning of each line in 'temp.txt'."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.

This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Text inserted at the beginning of each line in 'temp.txt' successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
New Text - This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.
New Text -
New Text - This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.

Explanation:

In the exercise above,

  • Check file existence:
    • Check if the file "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Text to insert:
    • Specifies the text to insert at the beginning of each line.
  • Insert text:
    • Use sed to insert the specified text at the beginning of each line.
    • The command sed "s/^/$insert_text/" temp.txt replaces the start of each line (^) with the specified text.
  • Replace the Original File:
    • Replace the original "temp.txt" with the file containing the inserted text.
  • Check for Success:
    • Checks if insertion was successful by examining the exit status.
    • If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

9.

Insert text at the end of each line:

Write a Bash script that inserts text at the end of each line in a text file named "file.txt".

Code:

#!/bin/bash

# Check if the file exists
if [ ! -f "temp.txt" ]; then
    echo "Error: File 'temp.txt' not found."
    exit 1
fi

# Text to insert at the end of each line
insert_text=" Text inserted at the end"

# Use sed to insert text at the end of each line and save the result to a temporary file
sed "s/$/$insert_text/" temp.txt > temp_with_insert.txt

# Replace the original file with the one containing the inserted text
mv temp_with_insert.txt temp.txt

# Check if insertion was successful
if [ $? -eq 0 ]; then
    echo "Text inserted at the end of each line in 'temp.txt' successfully."
else
    echo "Failed to insert text at the end of each line in 'temp.txt'."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/.

This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Text inserted at the end of each line in 'temp.txt' successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is http://www.gnu.org/software/bash/. Text inserted at the end
 Text inserted at the end
This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for Bash, Version 5.2. Text inserted at the end

Explanation:

In the exercise above,

  • Check file existence:
    • Check if the file "temp.txt" exists.
    • If not found, it prints an error message and exits with a non-zero status.
  • Text to insert:
    • Specifies the text to insert at the end of each line.
  • Insert text:
    • Use sed to insert the specified text at the end of each line.
    • The command sed "s/$/$insert_text/" temp.txt replaces the end of each line ($) with the specified text.
  • Replace the Original File:
    • Replace the original "temp.txt" with the file containing the inserted text.
  • Check for Success:
    • Checks if insertion was successful by examining the exit status.
    • If successful (exit status 0), it prints a success message. Otherwise, it prints a failure message.

Bash Editor:


More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Follow us on Facebook and Twitter for latest update.