- This is a single line substitution (
:s). To apply across the entire file use
- The pattern specifies alphanumeric (and underscore) words (
\w\+) anchored to the start (
^) and the end (
.* slurps up everything short of a final whitespace character (
\s). Without this whitespace
.* would slurp up all remaining characters except for a single
* is a "greedy" wildcard.
- By surrounding the start and end word in the pattern with
\) we can refer to them in the substitution with
\2. These are called "back references".
Improving things, I prefer 'very magic' mode to make the pattern easier to read. And I'd probably use a stricter version where only lines entirely made up of whitespace separated words are allowed:
Note: with mention of
awk I thought at first OP was trying to do this on the command line so I provided the following...
Command line version that updates the file:
vim -e +'%s/^\(\w\+\).*\s\(\w\+\)$/\1 \2/' +'wq' file
Using typical command line semantics (pipe to stdin, print to stdout) to just display the changes:
cat file | vim -e +'%s/^\(\w\+\).*\s\(\w\+\)$/\1 \2/p' +'q!' /dev/stdin