w3resource

Bash Manipulating text files exercises

1.

Count Lines in a File:

Write a Bash script that counts the number of lines in a text file named "document.txt".

Code:

#!/bin/bash

# Count the number of lines in the file "document.txt"
num_lines=$(wc -l < document.txt)

echo "Number of lines in 'document.txt': $num_lines"

Output:

Number of lines in 'document.txt': 5

Explanation:

In the exercise above,

  • wc -l < document.txt: This command counts the number of lines in the file "document.txt".
  • The output of wc -l is redirected to a variable num_lines.
  • Finally, the script prints the number of lines in the file.

2.

Count Words in a File:

Write a Bash script that counts the number of words in a text file named "document.txt".

Code:

#!/bin/bash

# Count the number of words in the file "data.txt"
num_words=$(wc -w < document.txt)

echo "Number of words in 'document.txt': $num_words"

Output:

Number of words in 'document.txt': 96

Explanation:

In the exercise above,

  • wc -w < data.txt: This command counts the number of words in the file "'document.txt".
  • The output of wc -w is redirected to a variable num_words.
  • Finally, the script prints the number of words in the file.

3.

Count Characters in a File:

Write a Bash script that counts the number of characters in a text file named "document.txt".

Code:

#!/bin/bash

# Count the number of characters in the file "document.txt"
num_chars=$(wc -m < document.txt)

echo "Number of characters in 'document.txt': $num_chars"

Output:

Number of characters in 'document.txt': 628

Explanation:

In the exercise above,

  • wc -m < document.txt: This command counts the number of characters in the file "document.txt".
  • The output of wc -m is redirected to a variable 'num_chars'.
  • Finally, the script prints the number of characters in the file.

4.

Search for a String:

Write a Bash script that searches for a specific string (provided as an argument) in a text file named "document.txt".

Code:

#!/bin/bash

# Check if the number of arguments is less than 1
if [ $# -lt 1 ]; then
    echo "Usage: $0 <search_string>"
    exit 1
fi

# Search for the provided string in the file "document.txt"
search_string="$1"
grep -q "$search_string" document.txt

# Check the exit status of grep
if [ $? -eq 0 ]; then
    echo "String '$search_string' found in 'document.txt'."
else
    echo "String '$search_string' not found in 'document.txt'."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh dynamically scoped
String 'dynamically' found in 'document.txt'.

Explanation:

In the exercise above,

  • The script checks if the number of arguments provided is less than 1. If so, it prints the usage and exits.
  • The provided search string is stored in the variable 'search_string'.
  • grep -q "$search_string" document.txt searches for the provided string in the file "document.txt" quietly (without outputting results to the terminal).
  • The exit status of "grep" is checked. If it's 0, the string is found, otherwise, it's not found.

5.

Replace Text:

Write a Bash script that replaces all occurrences of a word with another word in a text file named "output.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 output.txt
sed -i "s/$old_word/$new_word/g" output.txt

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

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh error.log err.log
All occurrences of 'error.log' replaced with 'err.log' in 'output.txt'.

Explanation:

In the exercise above,

  • The script first checks if the number of arguments provided is not equal to 2. If not, it prints the usage and exits.
  • It stores the old word and the new word in variables.
  • sed -i "s/$old_word/$new_word/g" output.txt replaces all occurrences of the old word with the new word in the file "output.txt". The -i option allows in-place editing of the file.
  • Finally, it prints a message indicating that all occurrences have been replaced.

6.

Sort Lines in a File:

Write a Bash script that sorts the lines in a text file named "out.txt" alphabetically.

Code:

#!/bin/bash

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

# Sort the lines alphabetically and save the result to a temporary file
sort "out.txt" > "out_sorted.txt"

# Overwrite the original file with the sorted contents
mv "out_sorted.txt" "out.txt"

echo "Lines in 'out.txt' sorted alphabetically."

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Lines in 'out.txt' sorted alphabetically.

Explanation:

In the exercise above,

  • The script first checks if the file "out.txt" exists.
  • It then uses the "sort" command to sort the lines in "out.txt" alphabetically. The sorted output is redirected to a temporary file "out_sorted.txt".
  • Finally, it replaces the original "out.txt" with the sorted contents from "out_sorted.txt".
  • A message is printed indicating that the lines in "out.txt" have been sorted alphabetically.

7.

Extract Text Between Tags:

Write a Bash script that extracts text between specified HTML tags from a file named "jsbin.html".

Content of HTML File:

Code:

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
<h1>JS Bin Editor</h1>
</body>
</html>

Code:

#!/bin/bash

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

# Define the start and end tags
start_tag="<h1>"
end_tag="</h1>"

# Extract text between the specified HTML tags using awk
extracted_text=$(awk -v start="$start_tag" -v end="$end_tag" '$0 ~ start, $0 ~ end {gsub(/<\/?h1>/, ""); print}' "jsbin.html")

# Print the extracted text
echo "$extracted_text"

Output:

JS Bin Editor

8.

Concatenate Files:

Write a Bash script that concatenates the contents of two text files named "file1.txt" and "file2.txt" into a new file named "file.txt".

Code:

#!/bin/bash

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

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

# Concatenate the contents of file1.txt and file2.txt into file.txt
cat file1.txt file2.txt > file.txt

# Check if concatenation was successful
if [ $? -eq 0 ]; then
    echo "Contents of file1.txt and file2.txt concatenated into file.txt."
else
    echo "Failed to concatenate files."
fi

Output:

Contents of file1.txt and file2.txt concatenated into file.txt.

Explanation:

In the exercise above,

  • Checking file existence: The script checks if both "file1.txt" and "file2.txt" exist using the -f test in the conditional statements.
  • Concatenating files: If both files exist, their contents are concatenated into a new file named "file.txt" using the "cat" command. The '>' operator is used to redirect the output of "cat" to the new file.
  • Checking concatenation success: After concatenation, the script checks the exit status ($?) to determine if the operation was successful ($? -eq 0). If successful, it prints a message indicating successful concatenation; otherwise, it prints a failure message.

9.

Remove Empty Lines:

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

Code:

#!/bin/bash

# Remove empty lines from the text file "document.txt"
grep -v '^$' document.txt > temp.txt
mv temp.txt document.txt

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

Output:

Empty lines removed from 'document.txt' successfully.

Explanation:

In the exercise above,

  • grep -v '^$' document.txt > temp.txt: This command uses "grep" to search for lines that are not empty (-v '^$') in the file "document.txt" and redirects the output to a temporary file named "temp.txt". The regular expression '^$' matches empty lines.
  • mv temp.txt document.txt: This command moves the contents of "temp.txt" back to "document.txt", effectively overwriting the original file with the one containing non-empty lines.
  • The "if" statement checks if the previous command was successful by examining the exit status '$?'. If the exit status is 0, it indicates success, and a corresponding message is printed. Otherwise, it indicates failure.

10.

Convert Text to Uppercase:

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

Content of file1.txt:

Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. The shell's name is an acronym for Bourne-Again SHell, a pun on the name of the Bourne shell that it replaces and the notion of being "born again".

Code:

#!/bin/bash

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

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

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

Output:

ad@DESKTOP-3KE0KU4:~$ cat file1.txt
BASH IS A UNIX SHELL AND COMMAND LANGUAGE WRITTEN BY BRIAN FOX FOR THE GNU PROJECT AS A FREE SOFTWARE REPLACEMENT FOR THE BOURNE SHELL. THE SHELL'S NAME IS AN ACRONYM FOR BOURNE-AGAIN SHELL, A PUN ON THE NAME OF THE BOURNE SHELL THAT IT REPLACES AND THE NOTION OF BEING "BORN AGAIN".

Explanation:

In the exercise above,

  • awk '{print toupper($0)}' file1.txt > temp.txt: This command uses awk to convert each line of text in "file1.txt" to uppercase using the toupper function and then redirects the output to a temporary file named "temp.txt".
  • mv temp.txt file1.txt: This command replaces the original "file1.txt" with the temporary file "temp.txt", effectively saving the changes.
  • The if statement checks if the previous command was successful by examining the exit status $?. If the exit status is 0, it indicates success, and a corresponding message is printed. Otherwise, it indicates failure.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/bash-script-exercises/manipulating-text-files.php