Select first word from each line in multiple lines with Vim

Relying on the external cut program:

:'<,'>!cut -d' ' -f1

You could append every first word to an empty register (let's say q) using

:'<,'>norm! "Qyiw

That is, in every line of the visual selection, execute the "Qyiw sequence of normal commands to append (the first) "inner word" to the q register.

You need to have > in cpoptions for the newline to be added in between yanks (:set cpoptions+=>), otherwise the words will be concatenated on a single line.

If you want to quickly empty a register you can use qqq in normal mode (or qaq to empty register a).

Note: the unnamed register ("") will also contain what you want at the end of the operation, so you don't need to "qp to paste it, p will do.


I think the chosen answer is a really good one, the idea of appending matches to registers can be pretty useful in other scenarios as well.

That said, an alternative way to get this done might be to align the right-hand side first, do the copying and then undo the alignment. You can use a tool like tabular, Align or easy-align.

With tabular, marking the area and executing :Tab/: would result in this:

apiKey        : = fmt.Sprintf("&apiKey=%s", args.ApiKey)
maxCount      : = fmt.Sprintf("&maxCount=%d", args.MaxCount)
id            : = fmt.Sprintf("&id=%s", args.Id)
userid        : = fmt.Sprintf("&userid=%s", args.Userid)
requestFields : = fmt.Sprintf("&requestFields=%s", args.RequestFields)

You can now use visual block mode to select the first part, and then use u to undo the alignment.

Tags:

Vim