Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete to end of line after a match, keep lines not matched

I have a file of the following form:

interesting text-MIB blah blah blah
VERY INTERESTING TEXT
interesting text-MIB blah blah blah

In each line containing the "-MIB" string, I would like to delete the text following this string, until the end of the line.

The following command seems to work as intended:

sed -i -n -e 's/-MIB.*$/-MIB/p' ./myfile

My problem is that it also deletes the lines where my pattern is not found. Here, the line "VERY INTERESTING TEXT" would be deleted. I am not really familiar with sed. What am i doing wrong? Is sed appropriate for this kind of treatment?

like image 784
Youri_Margarine Avatar asked Jun 25 '13 12:06

Youri_Margarine


People also ask

How to delete particular line using sed?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How to delete few lines from a file in unix?

To Remove the lines from the source file itself, use the -i option with sed command. If you dont wish to delete the lines from the original source file you can redirect the output of the sed command to another file.


2 Answers

sed -n option suppresses the default printing which is later enabled if you put p option after your sed statement.

In your example above, what you are telling sed is to suppress printing of all lines and then print only those lines where substitution has been done successfully. As a result the line where no substitution is made is never printed.

You need remove the -n option and p from your command:

sed -ie 's/-MIB.*$/-MIB/' ./myfile
like image 189
jaypal singh Avatar answered Jan 01 '23 18:01

jaypal singh


I have edited your sed. Try this,

sed -i.bak 's/-MIB.*$/-MIB/g' ./myfile

Here,

-i - will do the changes in original file and takes the backup of original file in .bak extension

like image 39
sat Avatar answered Jan 01 '23 19:01

sat