1

I want to ask you if you know how to delete lines in single file using sed command on Linux.

For example I have got file:

 something something- somethingelse 

And I want create sed command to delete all lines where line contains "something", but also I dont want delete line where is something-. Where is specific char like "-". Thank you for advice.

I tried to make something like sed -i "/something/d".

    2 Answers 2

    3
    sed -e '/something[^-]/d' -e '/something$/d' -i "$file" 

    even shorter, proposed by Philippos:

    sed -i '/something\([^-].*\)*$/d' "$file" 
    1
    • Note that this would delete a line saying something something-.
      – Kusalananda
      CommentedAug 23, 2021 at 10:03
    1

    Assuming it is more important to keep lines that contain something- than it is to delete lines that contain something:

    sed '/something/ { /something-/!d; }' file 

    This finds all lines containing the string something, and deletes all of those lines unless they also contain something-.

    Testing:

    $ cat file something something blah blah something something- blah blah somethingelse something something- 
    $ sed '/something/ { /something-/!d; }' file something something- blah blah something- 
    1
    • Or, almost equivalently (but a few characters shorter, and with no negation), sed '/something-/n; /something/d;'CommentedSep 1, 2021 at 7:01

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.