Reputation: 1013
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
Upvotes: 2
Views: 2227
Reputation: 4898
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
.
Upvotes: 0
Reputation: 9256
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$
Upvotes: 1
Reputation: 563
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
Upvotes: 0
Reputation: 4991
How about that:
:%s/HERE.*//
This pattern replaces the part of the line starting with HERE
and replaces it with nothing.
Upvotes: 8