Bash scripting - How to delete lines of a file?

 



In this tutorial, we play with deleting some lines of a file using Bash.

Content
  • Create a simple file for the tutorial
  • How to delete n-th line?
  • How to delete several lines within a range?
  • How to delete lines with patterns?

Create a simple file for the tutorial. 


First, let's create a simple file for this tutorial using the following command with seq and tee.

$seq 6 | tee delete.txt

1
2
3
4
5
6


How to delete n-th line? with sed

$sed '5d' delete.txt	# delete 5th line
Output:

1
2
3
4
6

$sed '$d' delete.txt	# delte the last line, $ inidicates the last line in sed
Output:

1
2
3
4
5


How to delete several lines within a range?

$sed '2,4d' delete.txt
Output:

1
5
6


How to delete lines with patterns?

$sed '/2/d' delete.txt	# /pattern/ to delete
Output:

1
3
4
5
6

No comments:

Post a Comment