Home Linux Shell Script to read given no of lines in file

Shell Script to read given no of lines in file

by Anup Maurya
2 minutes read

Shell script that accepts a filename and starting/ending line numbers as arguments, and displays all the lines between the given line numbers.

What does $# mean in Unix?

$# is the number of arguments, but remember it will be different in a function. $# is the number of positional parameters passed to the script, shell, or shell function. This is because, while a shell function is running, the positional parameters are temporarily replaced with the arguments to the function.

Shell Script to read given no of lines in file

#!/bin/bash

if [ $# -ne 3 ]; then
    echo "Usage: $0 <filename> <start_line> <end_line>"
    exit 1
fi

filename=$1
start_line=$2
end_line=$3

if [ ! -f $filename ]; then
    echo "$filename does not exist"
    exit 1
fi

if [ $start_line -gt $end_line ]; then
    echo "Start line number must be less than or equal to end line number"
    exit 1
fi

current_line=1

while read line; do
    if [ $current_line -ge $start_line ] && [ $current_line -le $end_line ]; then
        echo $line
    fi
    ((current_line++))
done < $filename

How you can use the script

$ ./script.sh Test.txt 5 10

This will display lines 5 through 10 of Test.txt. If the file doesn’t exist, or the start line number is greater than the end line number, the script will exit with an error message.

Test.txt file

Linux is a free and open-source operating system.
It was first released in 1991 by Linus Torvalds.
It is based on the Unix operating system.
It is widely used for servers, supercomputers and more.
Linux provides a stable, secure, and customizable platform.
Designed to work well with a wide range of hardware and software.

Output

~/Assignment$ bash main.sh 
Usage: main.sh <filename> <start_line> <end_line>
~/Assignment$ bash main.sh Test 1 4
test does not exist
~/Assignment$ bash main.sh Test.txt 1 4
Linux is a free and open-source operating system.
It was first released in 1991 by Linus Torvalds.
It is based on the Unix operating system.
It is widely used for servers, supercomputers and more.
~/Assignment$ bash main.sh Test.txt 6 4
Start line number must be less than or equal to end line number
~/Assignment$ bash main.sh Test.txt 6 
Usage: main.sh <filename> <start_line> <end_line>
~/Assignment$ bash main.sh book.txt 6 10 
book.txt does not exist
~/Assignment$ 

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

related posts

Leave a Comment

Enable Notifications OK No thanks