How to append some command output at the end of each line in a Vi file?

Deadly 提交于 2019-12-11 17:56:00

问题


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

回答1:


With awk:

$ awk '{NF=NF+1; $NF=$2}1' file
abc 123 pqr 123
lmn 234 rst 234
jkl 100 mon 100

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

awk '{print $0, $2}' file

It prints the full line plus the second field.

Or even shorter, thanks Håkon Hægland!:

awk '{$(NF+1)=$2}1' file



回答2:


You have many ways to do that in Vi(m). This is the simplest that comes to my mind:

:%norm 0f<space>yaw$p

Explanation:

  • :{range}norm command executes normal mode command 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 buffer
  • 0 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 line
  • yaw yanks the word and the <space> under the cursor
  • $ jumps to the end of the line
  • p pastes the previously yanked text



回答3:


prompt with mark, you can do it in vi

:%s/\( [^ ]*\)\(.*\)/\1\2\1/

Another way, Using sed

sed -r 's/( [^ ]*)(.*)/\1\2\1/' file


来源:https://stackoverflow.com/questions/21624505/how-to-append-some-command-output-at-the-end-of-each-line-in-a-vi-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!