Write a Bash Script to Print a Particular Line From a File
Last Updated :
04 Oct, 2024
One useful tool for automating operations in Unix-based systems is bash scripting. The need to print a certain line from a file is one such requirement. This post will walk you through writing a basic Bash script that accomplishes that. The fundamentals of utilizing conditional statements, showing the intended output, and reading user input will all be covered.
Prerequisites
Before we begin to write the script, make sure you have:
- A Unix-based operating system (Linux, macOS, etc.)
- A text editor (like Nano, Vim, or any other preferred editor)
How to Write a Bash Script to Print a Particular Line from a File?
Below is the how-to Write a bash script to print a particular line from a file.
Step-by-Step Guide
1. Create the Bash Script File
Open your terminal and create a new file for your script. We’ll call it print_line.sh
. You can create this file using the touch
command or by directly opening it in a text editor.
Command: touch print_line.sh
2. Open the Script in a Text Editor
Now, open the script in your preferred text editor. For example, if you are using nano, you can type:
nano print_line.sh
3. Write the Shebang
At the top of the script, add the shebang line. This line tells the system which interpreter to use to execute the script.
#!/bin/bash
Next, we’ll add commands to read the filename and the line number from the user. We will also check if the file exists.
echo "Enter the filename:"
read filename
if [[ ! -f $filename ]]; then
echo "File not found!"
exit 1
fi
echo "Enter the line number you want to print:"
read line_number
5. Print the Specified Line
Now, we will use the sed
command to print the specified line from the file. The sed
command is a stream editor that can perform basic text transformations.
line_content=$(sed -n "${line_number}p" "$filename")
echo "Line $line_number: $line_content"
6. Complete Script
Your complete script should look like this:
#!/bin/bash
echo "Enter the filename:"
read filename
if [[ ! -f $filename ]]; then
echo "File not found!"
exit 1
fi
echo "Enter the line number you want to print:"
read line_number
line_content=$(sed -n "${line_number}p" "$filename")
echo "Line $line_number: $line_content"
7. Save and Exit
If you are using nano
, save your changes by pressing CTRL + O
, then hit Enter
, and exit by pressing CTRL + X
.
8. Make the Script Executable
Before you can run the script, you need to make it executable. Use the following command:
chmod +x print_line.sh
9. Run the Script
Now you can execute your script. Run it by typing:
./print_line.sh
When prompted, enter the filename and the line number you wish to print. For example:
- Enter the filename: sample.txt
- Enter the line number you want to print: 3
If the file exists and the line number is valid, the script will output the specified line.
Conclusion
An easy way to showcase the capabilities of shell scripting is to create a Bash script that prints a specific line from a file. This script is easily customizable for more complex tasks or may be integrated into larger scripts for automation by using simple commands and user input.
Similar Reads
Bash Scripting - How to read a file line by line
In this article, we are going to see how to read a file line by line in Bash scripting. There might be instances where you want to read the contents of a file line by line using a BASH script. In this section, we will look at different ways to do just that. We will use BASH commands and tools to ach
3 min read
How to extract paragraph from a website and save it as a text file?
Perquisites: Â Beautiful soupUrllib Scraping is an essential technique which helps us to retrieve useful data from a URL or a html file that can be used in another manner. The given article shows how to extract paragraph from a URL and save it as a text file. Modules Needed bs4: Beautiful Soup(bs4)
2 min read
Reading Lines by Lines From a File to a Vector in C++ STL
Prerequisites: STL in C++Vector in C++File handling in C++ The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. Vector in C
2 min read
Shell Script to Read Data From a File
File reading is quite an important task in a Programmer's life as it makes some tasks quite comfortable and automates certain repetitive and time-consuming things. File reading is quite an interesting concept to learn as it gives insight into quite a lot of things that can be done in the Programming
3 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string
5 min read
Bash Scripting - Introduction to Bash and Bash Scripting
Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System. It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them
12 min read
How To Pass and Parse Linux Bash Script Arguments and Parameters
Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We'll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script. Pa
7 min read
Write to a File From the Shell
Writing files in the shell might sound complex, but it's simple, and once you understand it will be at your fingertips. Whether you're saving data, creating files, or editing existing ones, here's a simple guide to help you with file writing in the shell. This article makes you aware of everything a
3 min read
Bash Script - Define Bash Variables and its types
Variables are an important aspect of any programming language. Without variables, you will not be able to store any required data. With the help of variables, data is stored at a particular memory address and then it can be accessed as well as modified when required. In other words, variables let yo
12 min read
Bash Scripting - Write Output of Bash Command into Log File
Let there are some situations in which you have to save your output in a file ( generally called log file). Output can be user details ( username, password, Gmail, etc. ), products record ( buying or selling any goods ), or simply any kind of data that you can store in a log file. Let see how to wri
4 min read