How to search for a string in a line, then delete to end of line from there

StackOverflow https://stackoverflow.com/questions/23516759

  •  17-07-2023
  •  | 
  •  

سؤال

I have a requirement which I am sure I can do in vi (plenty of other solutions I am sure), and this is it.

I have a file that looks like this

1234 Some Text HERE rest of line
1235 Some Other Text HERE rest of line

What I want to do is delete text from, and including the word HERE to the end of the line, leaving me with this;

1234 Some Text
1235 Some Other Text

I have done search and replace things in vi, but am not sure how to do a search then run a command.

Any help, as always is greatly appreciated.

Thanks in anticipation

هل كانت مفيدة؟

المحلول 3

As always, in vi there are many ways to skin this particular cat. As has already been stated, a simple solution to exactly this problem is:

:%s/HERE.*//

However, to answer your more general question:

I have done search and replace things in vi, but am not sure how to do a search then run a command.

you want the :g[lobal] command:

:[range]g[lobal]/{pattern}/[cmd]

        Execute the Ex command [cmd] (default ":p") on the
        lines within [range] where {pattern} matches.

This would actually be more long-winded for your exact example, but for tasks such as deleting lines that match a specific pattern, it is considerably more concise.

e.g. if you wanted to instead delete all lines that contain HERE, you would run:

:g/HERE/d

Factoid: this command form is the origin of grep's name: g/re/p, shorthand for global/{regex}/print.

نصائح أخرى

How about that:

:%s/HERE.*//

This pattern replaces the part of the line starting with HERE and replaces it with nothing.

The combination of d$ will delete from the cursor to the end of the current line. So if you're searching using the / command, it'll be...:

/HERE<enter>d$

This can be done using sed also:

sed "s/HERE.*//"

Example:

echo "this is a test HERE test" | sed "s/HERE.*//"

Result:

this is a test
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top