hyun.ji
hyun.ji

Reputation: 59

Merge two files and specify fields using awk

I want to merge two files and output them.

So file0.txt and file1.txt are merged.

However, the column of file1.txt is appended to the end.

$ cat  file0.txt 
   Name: vSwitch0    MTU: 1500    Uplinks: vmnic0    Portgroups: VM Network, Management Network
   Name: vSwitch1    MTU: 1500    Uplinks: vmnic1    Portgroups: VM Network 2
   Name: vSwitch2    MTU: 1500    Uplinks: vmnic2    Portgroups: VM Network 3

$ cat  file1.txt 
vmnic2  nvmxnet3  Down  0  half
vmnic0  nvmxnet3  Up  10000  full
vmnic1  nvmxnet3  Up  10000  full
$ awk 'NR==FNR { temp[FNR]=$2 FS $3 FS $4 FS $5; next }; {print ($0) " " temp[FNR]}' <(sort file1.txt)  <(sort file0.txt)

   Name: vSwitch0    MTU: 1500    Uplinks: vmnic0    Portgroups: VM Network, Management Network **nvmxnet3 Up 10000 full**
   Name: vSwitch1    MTU: 1500    Uplinks: vmnic1    Portgroups: VM Network 2 **nvmxnet3 Up 10000 full**
   Name: vSwitch2    MTU: 1500    Uplinks: vmnic2    Portgroups: VM Network 3 **nvmxnet3 Down 0 half**

I've tried but failed. I want to do something like below

However, I don't want to use join or paste.. I will only using awk command .

   Name: vSwitch0    MTU: 1500    Uplinks: vmnic0  **nvmxnet3  Up   10000 full**  Portgroups: VM Network, Management Network 
   Name: vSwitch1    MTU: 1500    Uplinks: vmnic1  **nvmxnet3  Up   10000 full**  Portgroups: VM Network 2 
   Name: vSwitch2    MTU: 1500    Uplinks: vmnic2  **nvmxnet3  Down 0  half**      Portgroups: VM Network 3 

OR

Second my question

Is it even possible like this?

cat file1.txt 

vmnic0  nvmxnet3  Up   10000  Full
vmnic1  nvmxnet3  Up   10000  Full
vmnic2  nvmxnet3  Down 0      Half
vmnic3  nvmxnet3  Up   10000  Full

# cat file2.txt 
Name: vSwitch0    MTU: 1500    Uplinks: vmnic0            Portgroups: VM Network, Management Network
Name: vSwitch1    MTU: 1500    Uplinks: vmnic1            Portgroups: VM Network 2
Name: vSwitch2    MTU: 1500    Uplinks: vmnic3, vmnic2    Portgroups: VM Network 3

Is it possible to output something like this?

vmnic0  nvmxnet3  Up   10000  Full  Name: vSwitch0  MTU: 1500  Portgroups: VM Network, Management Network
vmnic1  nvmxnet3  Up   10000  Full  Name: vSwitch1  MTU: 1500  Portgroups: VM Network 2
vmnic2  nvmxnet3  Down 0      Half  Name: vSwitch2  MTU: 1500  Portgroups: VM Network 3
vmnic3  nvmxnet3  Up   10000  Full  Name: vSwitch2  MTU: 1500  Portgroups: VM Network 3

Upvotes: 0

Views: 68

Answers (1)

KamilCuk
KamilCuk

Reputation: 140960

Replace Portgroups with the text you want to add.

awk '
NR==FNR { temp[FNR]=$2 FS $3 FS $4; next }
{gsub(" Portgroups:", temp[FNR]" Portgroups:"; print}
' <(sort file1.txt)  <(sort file0.txt)

Upvotes: 1

Related Questions