Hello, friends. The more we know how to use the terminal, the more we can benefit from it. That’s why today you will learn how to delete a range of lines from a text file using the terminal.
Although it seems like a solution that may not be useful, the reality is that in scripts and configuration files, learning how to manage files can be a great help to you.
For this, you can use two simple commands to make the desired range of lines disappear. As I said, this is important to further outline the text files.
Let’s go for it.
How to remove a range of lines from a text file using the terminal
Fortunately, the process is basic thanks to two commands that will get the job done if you know how to use them correctly.
First, I will create a test file and add 10 lines. The configuration of this file is.
Line1 Line2 Line3 Line4 Line5 Line6 Line7 Line8 Line9 Line10
With this example, we can get started.
Deleting a range of lines from a text file with the awk command
The awk command is a very useful command on Linux. It allows you to extract the columns of a line or several lines from a text file. Therefore, it could be used for our purpose.
Suppose in the above example we want to remove the range of lines from 4 to 8.
Then you have to run
awk 'NR < 4 || NR > 8' file.txt
You will get an output screen like this
That’s how fast you can do it.
The same process but using the gawk command
The gawk command is an implementation of the GNU
awk project, so you could say it is a more advanced version of it.
However, the process is somewhat similar
gawk -i inplace 'NR < 4 || NR > 8' file.txt
This way, the process is just as straightforward
I hope this little trick will help you sometime.