Shell Script to Displays All the Lines Between the Given Line Numbers
In this article, We will write a shell script to display all lines between given line numbers to console.
We have a file name and start and end line, We have to write a script that will print all the lines from the specified start line to the ending line of the file.
File : a.txt Line 1 : Hello Line 2 : GeeksForGeeks Line 3 : Hritik Line 4 : Hello GFG Line 5 : Hello Hritik start line, s = 2 end line, e = 4 Output : Line 2 : GeeksForGeeks Line 3 : Hritik Line 4 : Hello GFG
- First, create a file main.sh using cat or any file creation command.
- Take user input with the read command
- Now we will use a tool sed
We will use the tool sed which is used to output the contents to the console. Sed is passed a -n flag to choose which lines are output to the console.
Syntax: sed -n <start>,<end>\p <filename>
file = a.txt, s = 2 and e = 4 sed -n 2,4\p a.txt
After writing and saving the code, use the following command to give permission to file
chmod 777 a.txt
It will give Read, Write and Execute permission to the user.
Below is the implementation:
//Shell script to display all the //given lines of a file //take file name from user //and store the input in f variable echo "Enter the file name :" read f //take starting line from user //and store the input in s variable echo "Enter the starting line :" read s //take endinging line from user //and store the input in e variable echo "Enter the ending line :" read e //printing the specified lines to console. sed -n $s,$e\p $f