How to Count Lines in a File in Shell Script

Shell Scripting @ Freshers.in

Counting the number of lines in a file is a common task in shell scripting. Whether you are a seasoned developer or just starting with shell scripting, knowing how to count lines in a file is a fundamental skill. In this article, we will walk you through the process of writing a shell script to count the lines in a file named ‘data.txt.’

Before we dive into creating the shell script, you need to ensure you have the following:

  1. A Unix-like operating system (Linux, macOS, or a compatible environment on Windows).
  2. A text editor (such as Vim, Nano, or VSCode) for creating and editing shell scripts.
  3. Basic knowledge of shell scripting.

To begin, open your terminal. You will be writing the shell script using a text editor of your choice within the terminal.

Create the Shell Script

Use your preferred text editor to create a new file. You can name the file something like ‘count_lines.sh.’ Here’s an example of how to create it using the nano text editor:

nano count_lines.sh

Write the Script

Inside the ‘count_lines.sh’ file, write the following shell script:

#!/bin/bash
# Specify the file name
file="data.txt"
# Use the 'wc' command to count lines
line_count=$(wc -l < "$file")
# Print the line count
echo "The number of lines in $file is: $line_count"

This script sets the file variable to ‘data.txt,’ uses the wc (word count) command with the -l flag to count lines in the specified file, and then prints the line count.

Save and Exit

Save the file and exit the text editor. In nano, you can do this by pressing Ctrl + O to save and Ctrl + X to exit.

Make the Script Executable

Before running the script, you need to make it executable. Use the following command to do so:

chmod +x count_lines.sh

Now that the script is executable, you can run it to count the lines in ‘data.txt’:

./count_lines.sh

Read more on Shell and Linux related articles

Other urls to refer

  1. PySpark Blogs
Author: user