Home arrow Journal arrow Today Quick Tip: Replacing a line with sed
Today Quick Tip: Replacing a line with sed PDF
Saturday, 02 April 2011

Sed is a powerfull UNIX tool used to process/edit streams. If you need to replace/delete strings in a text file for example sed is your friend.

Delete a line from a file
a. Delete a line that contains a pattern

To delete a line that contains "line with a pattern to delete" use:

  sed '/$line with a pattern to delete/d' textfile >textfile2

In the previous command the text that appears after /$ is the pattern text contain in the line that you want to delete. The d after that string, separated by / means to delete that line. All this is happening in textfile file.

If the line contain special characters (or spaces) use -e switch:

  sed -e '/$key words/d' textfile >textfile2

b. Delete a particular line, by line number
If you want to delete a particular line (for example line 15):

  sed '15d' textfile >textfile2

c. Delete lines from 10 to 20:
If you want to delete multiple lines starting with line 10 and ending with line 20 use:

   sed '10,20d' textfile >textfile2

d. Delete last line from a file
Next command will remove last line from a file:

  sed '$d' textfile >textfile2

Last Updated ( Saturday, 02 April 2011 )
< Prev   Next >

Other BSD Systems





Best BSD firewall?