Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Linux Commands»How to Delete a Line Containing Specific String using SED

    How to Delete a Line Containing Specific String using SED

    By RahulNovember 24, 20221 Min Read

    Syntax:

    sed -i '/string_to_delete/d' /path/to/file
    

    SED is a Stream Editor having the capability to remove lines from files containing a specific string. Using -i with sed we can remove lines in the same file.

    Advertisement

    Example 1:

    Remove all lines from /var/log/messages containing the string “DELETE THIS TEXT” and restore output in a new file. Do not make any changes to the original line.

    $ sed "/DELETE THIS TEXT/d" /var/log/messages > messages.txt
    

    Example 2:

    Remove all lines from /var/log/messages containing the string “DELETE THIS TEXT” in the same file.

    $ sed -i "/DELETE THIS TEXT/d" /var/log/messages
    

    delete file sed string
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Top 10 JQ Commands Every Linux Developer Should Know

    How to Check if a Program Exists in Linux

    How to Create a Directory If It Does Not Exist in Linux

    View 2 Comments

    2 Comments

    1. Jeremy Granger on May 10, 2022 7:18 pm

      It’s important to know how to do the redirection method because I work with older systems, like Solaris, and their version of sed is not so forgiving. I usually output (>) to a file like “file.tmp”, then “mv file.tmp file”

      I would add that: sed -i.tmp ‘/^startswith/d’ /dir/file would be optimal. I end up needing to delete files but not using that I often have mixed results on different OS’s. I think with the more modern systems you may be able to get away with -i alone?

      You can quote in ‘ or “. It would depend if you are want interpolation or not. Double quotes if you have a variable.

      Reply
    2. Rajesh Krishna Nandanwar on May 16, 2021 8:56 pm

      The syntax is incorrect. replace ‘ with ”

      sed -i “/Text to Delete/d’” /path/to/file

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to List Manually Installed Packages in Ubuntu & Debian
    • 10 Bash Tricks Every Developer Should Know
    • How to Validate Email Address in JavaScript
    • Firewalld: Common Firewall Rules and Commands
    • 12 Apk Commands in Alpine Linux Package Management
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.