Use a :s
command with a regular expression:
:%s/\v^\s*\S+(\s+(\S+).*)?/\2
The \v
tells Vim to use the "very magic" style of regexps, which is similar to extended regexps in grep, or pcre.
The regexp matches a single word at the start, possibly preceded by some optional whitespace. Then, after some more whitespace, the second word is captured inside group \2
. Finally, a .*
matches the whole rest of the line.
The part after the first word is optional (grouped in parentheses and made optional with the final ?
). This ensures lines with a single word will still be matched, and in this case they'll be replaced with a blank line, which I imagine is what should be expected of a line with a single word, since the second work is blank in that case. This is one advantage of using regexps for this task, as you get more control over what to do with lines that have corner cases.
Finally, group \2
is used for replacement. It captured the second word on the line, by itself.
You can then save the modified contents to the new filename:
:saveas new_file.txt
This will preserve your unmodified old_file.txt
and will make sure further modifications of the current buffer will only go to new_file.txt
.
awk
acceptable? Does it have to be from within vi/vim? – Jeff Schaller Jul 11 '19 at 14:58Jeff "data checker" Schaller
, where the 2nd field contains a quoted delimiter? – Jeff Schaller Jul 11 '19 at 15:20