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".

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
    Aug 23 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;' Sep 1 at 7:01
-1

Tried with awk

awk '!/something[^-]|something$/' filename >tmpfile && mv tmpfile filename

output

cat filename

something-
3
  • 1
    Why not use -i? And the question asks for sed, not awk... Aug 19 at 14:16
  • @StephenKitt: Why not use -i?  Because awk’s -i option is --include, which has no obvious relevance here.  (Don’t feel bad, I made the exact same mistake a couple of years ago.)  Yeah, posting an awk answer to a sed question is not ideal. Sep 1 at 6:51
  • @G-Man indeed, I got mixed up with inplace and the sed request in the question! Sep 1 at 7:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.