问题描述:

I have two files containing records as below:

File1:

1,2,3,a|x|z,4,5

And

File2:

1,2,3,a|x|z,4,5

1,2,3,a|x|z,4,5

1,2,3,a|x|z,4,5

1,2,3,a|x|z,4,5

Here there are 6 fields separated by ,

How can I replace the fourth field(i.e. a|x|z) in 2nd, 3rd and 4th line of File2 with a, x and z respectively from File1.

My real problem is, the fourth field wont be always a|x|z but it is always | separated

My considered output would be as below.

File2:

1,2,3,a|x|z,4,5

1,2,3,a,4,5

1,2,3,x,4,5

1,2,3,z,4,5

网友答案:
$ awk 'FNR==NR{split($4,f1,"|");next}FNR>1{$4=f1[FNR-1]}1' FS=, OFS=, file1 file2
1,2,3,a|x|z,4,5
1,2,3,a,4,5
1,2,3,x,4,5
1,2,3,z,4,5

Note: this assumes that number of sub-fields in file1 i.e 3 equals the number of lines to be replaced in file2 again 3 (lines 2,3,4). If this is not the case you should describe what should happen if says the number of sub fields is still 3 but the number of lines in file is 10?

相关阅读:
Top