My Board
How to Delete Lines From a Particular File Using the sed Command - Printable Version

+- My Board (https://ellohost.com/forum)
+-- Forum: Tutoriel EN (https://ellohost.com/forum/forumdisplay.php?fid=8)
+--- Forum: Others (https://ellohost.com/forum/forumdisplay.php?fid=20)
+--- Thread: How to Delete Lines From a Particular File Using the sed Command (/showthread.php?tid=730)



How to Delete Lines From a Particular File Using the sed Command - aaron - 09-08-2023


    How to Delete Lines From a Particular File Using the sed Command
   

How to Delete Lines From a Particular File Using the sed Command


   

The delete command removes lines from the current input file without opening the content. There are five sed scripts available:

   
           
  • Deleting a particular line of input using the d subcommand:
  •    
   
sed '#d' samplefile.txt
   

For example, to remove the first line from the cities.txt file, run the following:

   
sed '1d' cities.txt
   
           
  • Deleting multiple lines within a specific range:
  •    
   
sed '#,#d' samplefile.txt
   

Replace the # symbols with the start and end of the line range. For example, to delete the first, second, and third line from the cars.txt file, enter the following:

   
sed '1,3d' cars.txt
   
           
  • Deleting a file content’s last line:
  •    
   
sed '$d' samplefile.txt
   

For example, to remove the last line from the computers.txt file, run the following:

   
sed '$d' computers.txt
   
           
  • Deleting from the nth to the last line:
  •    
   
sed 'nth,$d' samplefile.txt
   

For example, to remove the second to the last input line from the books.txt file, enter:

   
sed '2,$d' books.txt
   
           
  • Deleting the pattern matching line:
  •    
   
sed '/pattern/d' samplefile.txt
   

For example, to remove the “oabo” pattern from the filestrings.txt file, run:

   
sed '/oabo/d' filestrings.txt