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
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 - 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
How To Run Bash Script In Linux? Bash scripts, also called shell scripts, are programs that help automate tasks by storing a series of commands that often go together, like updates or upgrades. These scripts make it easier to perform tasks automatically instead of typing each command manually. After creating a Bash script, you can
6 min read
Shell Script to Count Lines and Words in a File Linux provides users a great cool feature of the command-line tool along with a graphical user interface where they can perform tasks via ruining command. All of this command returns a status according to their execution. Its execution value can be used for showing errors or take some other action i
6 min read
Bash Scripting - How to Run Bash Scripting in Terminal In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we prin
2 min read
Shell Script to Perform Operations on a File Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file. For our convenience, we create a file named 'geeks.txt' and another .sh file (or
5 min read
Shell Script to Perform String Replacement in a File String replacement is the process of replacing a string with another in a particular block of code, text, or the entire file. There are instances where we need to replace one string with another, but there are a lot of instances of such strings. There are two solutions here; you can manually replace
6 min read