How to Delete Specific Lines from a File Using Line Numbers
When you're working with text files—be it config files, logs, or source code—you may need to delete specific lines based on their line numbers. This might sound intimidating, but it’s actually quite easy once you know which tool to use.
In this post, we’ll walk through several methods to remove lines using line numbers, using command-line tools like sed
, awk
, and even Python. Whether you're a beginner or a seasoned developer, there’s a solution here for you.
#
The Basic Idea
To delete a specific range of lines from a file:
- Identify the start line and end line.
- Use a tool or script to remove the lines between those numbers.
- Save the changes back to the original file.
Let’s break this down by method.
sed
(Stream Editor)#
1. Using 
sed
is a command-line utility that’s perfect for modifying files line-by-line.
#
Basic Syntax- Replace
START_LINE
andEND_LINE
with actual numbers. d
tellssed
to delete those lines.
#
ExampleTo delete lines 10 through 20:
#
With Variables📚 More on sed line deletion
awk
#
2. Using awk
is a pattern scanning tool. It’s ideal for skipping specific lines.
#
Syntax#
ExampleThis prints all lines except lines 10 through 20.
📚 Learn more about awk
head
and tail
#
3. Using Perfect when you only need to chop lines off the start or end.
#
ExampleDelete lines 10 to 20:
head -n 9
gets lines before line 10.tail -n +21
grabs everything from line 21 onward.
perl
#
4. Using perl
is great for more advanced file manipulation.
#
Syntax#
Example$.
is the line number variable inperl
.
#
5. Using PythonFor full control or if you’re already using Python in your workflow:
#
ExamplePython is especially useful if you need to add logic or conditions around what gets deleted.
📚 Working with files in Python
#
Conclusion
There are plenty of ways to delete lines from a file based on line numbers:
- Use
sed
for simple, fast command-line editing. - Choose
awk
for conditional line selection. - Go with
head
/tail
for edge-case trimming. - Try
perl
if you’re comfortable with regex and quick one-liners. - Opt for Python when you need logic-heavy, readable scripts.
Explore Nife.io for modern cloud infrastructure solutions, or check out OIKOS to see how edge orchestration is done right.