GermainGum
GermainGum

Reputation: 1399

Select first word from each line in multiple lines with Vim

I would like to copy the first words of multiple lines.

Example of code :

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)

I would like to have this in my clipboard :

apiKey
maxCount
id
userid
requestFields

I tried with ctrl-v and after e, but it copies like on the image : enter image description here

Upvotes: 12

Views: 4726

Answers (3)

Chris Stryczynski
Chris Stryczynski

Reputation: 33881

Relying on the external cut program:

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

Upvotes: 1

Marth
Marth

Reputation: 24802

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.

Upvotes: 10

anon
anon

Reputation:

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.

Upvotes: 2

Related Questions