Reputation: 956
I have a text file and I want to remove every word except the first word on every line and I have no idea how to do this.
So, if I have:
one two three
four five
six
I want to remain with:
one
four
six
Got any ideas?
Upvotes: 16
Views: 7234
Reputation: 16184
Alternatively, you can do it using a macro.
Type qa
in normal mode to start recording a macro in register a.
Then type 0elDj
to delete everything on the current line but the first word, and go to the next line.
Type q
again to end recording the macro.
Now you can fire the macro on any line with @a
.
Run :%norm! @a
to apply the macro to every line in the buffer.
This way you can repeat any complex operation you want, not just substituting. I love macros :)
EDIT: Note that it doesn't work when a line has strictly less than 2 characters. For this reason, this is generally not the best approach to this problem.
Upvotes: 2
Reputation:
A more robust solution is to filter it through a program that is really good at these kinds of manipulations: awk
.
Say you had this content:
one two three
four five
six
Run :%!awk '{print $1}'
and you will get:
one
four
six
awk
's default field separator character is a space, though you could change it to whatever you wanted, depending on what you needed.
Upvotes: 7
Reputation: 5149
If the lines don't start with whitespace, you could replace ' .*'
(which matches everything after the first word) with an empty string:
:%s/ .*//g
Upvotes: 20