Suppose I have a vi file as the following:
cat file1
abc 123 pqr
lmn 234 rst
jkl 100 mon
I want to take the 2nd field of each line (viz, in this case is 123, 234 and 100) and append it to the end of that same line. How will I do that?
The output should look like the following:
abc 123 pqr 123
lmn 234 rst 234
jkl 100 mon 100
You have many ways to do that in Vi(m). This is the simplest that comes to my mind:
Explanation:
:{range}norm command
executes normal modecommand
on each line in{range}
%
is a shortcut range meaning "all lines in the buffer" so we will execute what follows on every line in the buffer0
puts the cursor on the first column on the current line (not strictly necessary but good practice)f<space>
jumps the cursor on the first<space>
after the cursor on the current lineyaw
yanks the word and the<space>
under the cursor$
jumps to the end of the linep
pastes the previously yanked textprompt with mark, you can do it in vi
Another way, Using sed
With
awk
:It increments the number of field in one and sets the last one as the 2nd. Then
1
is a true condition, which is evaluated as the default awk behaviour:{print $0}
.Or also
It prints the full line plus the second field.
Or even shorter, thanks Håkon Hægland!: