Can sed delete lines?

Yes, sed can delete lines from a file or input stream. You can use the d command in sed to delete lines that match a specific pattern or to delete lines based on their line numbers.

Examples of Deleting Lines with sed

  1. Delete Lines Matching a Pattern: To delete lines that contain a specific string, you can use the following command:

    sed '/pattern/d' filename
    

    For example, to delete all lines containing the word "banana" from a file named fruits.txt, you would use:

    sed '/banana/d' fruits.txt
    
  2. Delete Specific Line Numbers: You can also delete lines by specifying their line numbers. For example, to delete the second line of a file:

    sed '2d' filename
    
  3. Delete a Range of Lines: To delete a range of lines, you can specify the starting and ending line numbers. For example, to delete lines 2 to 4:

    sed '2,4d' filename
    
  4. In-Place Deletion: If you want to delete lines directly in the file (in-place), you can use the -i option:

    sed -i '/pattern/d' filename
    

Example

Suppose you have a file example.txt with the following content:

apple
banana
cherry
date

To delete the line containing "banana", you would run:

sed '/banana/d' example.txt

The output would be:

apple
cherry
date

Using sed for deleting lines is a powerful way to manipulate text files directly from the command line.

0 Comments

no data
Be the first to share your comment!