How to append some command output at the end of ea

2019-08-27 15:39发布

问题:

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


标签: shell unix vim awk vi