Pages

Thursday, March 14, 2013

Unix Sed Command to Delete Lines in File - 15 Examples

In this article we will see how to delete or remove specific lines that contains a pattern or in a particular position in a file.

As an example, consider the below file with sample data:
> cat file
linux
unix
fedora
debian
ubuntu


1. Delete first line or header line
> sed '1d' file
unix
fedora
debian
ubuntu

The d command is to delete a line. 1d indicates remove the first line. Nd means delete Nth line.

Note that the above command prints the content of the file on the terminal by removing the first line. It actually wont remove the line from the file itself. To remove the line in the original file, use the -i option with sed command. The -i option works only with GNU sed.
> sed -i '1d' file

If you dont have a GNU sed installed, redirect the output of the command to another file.
> sed '1d' file > newfile

2. Delete last line or footer line or trailer line
> sed '$d' file
linux
unix
fedora
debian

Here $ in the above command indicates the last line.

3. Delete particular line. Removes second line our case.
> sed '2d' file
linux
fedora
debian
ubuntu

4. Delete range of lines.

Lets delete lines from 2 to 4. The range is indicated by a comma separated values.
> sed '2,4d' file
linux
ubuntu

5. Delete lines other than the first line or header line
> sed '1!d' file
linux

The ! operator is to negate the command.

6. Delete lines other than last line or footer line
> sed '$!d' file
ubuntu

7. Delete lines other than the specified range
> sed '2,4!d' file
unix
fedora
debian

Removes lines other than 2nd, 3rd and 4th.

8. Delete first and last line
> sed '1d;$d' file
unix
fedora
debian

The semicolon operator is to specify multiple conditions.

9. Delete empty lines or blank lines
> sed '/^$/d' file

The ^$ indicates sed command to delete empty lines. However, this sed wont remove the lines that contain spaces.

10. Delete lines that begin with particular character
> sed '/^u/d' file
linux
fedora
debian

^ is to specify the starting of the line. Above sed command removes all the lines that start with character 'u'.

11. Delete lines that end with particular character.
> sed '/x$/d' file
fedora
debian
ubuntu

$ is to indicate the end of the line. The above command deletes all the lines that end with character 'x'.

12. Delete lines which are in upper case or capital letters
> sed '/^[A-Z]*$/d' file

13. Delete lines that contain a pattern
> sed '/debian/d' file
linux
unix
fedora
ubuntu

14. Delete line starting from a pattern till the last line.
> sed '/fedora/,$d' file
linux
unix

15. Delete last line only if it contains the pattern
> sed '${/ubuntu/d;}' file
linux
unix
fedora
debian

Here $ indicates the last line. If you want to delete a particular line only if it contains a pattern, then put the number of the line in place of the $.

No comments:

Post a Comment