Replace any column in file with a column from a di

2019-08-17 05:16发布

问题:

I have two .dat files, f1.dat and f2.dat as below. I am trying to copy the column from f2.dat file to f1.dat file while retaining the format of f1.dat using shell script command.

File 1 (f1.dat)

# Off---=0.210
# Angle=-2.3
# Br    L1--    L2--    L3---
6     0.047   0.093   44.660
7     0.062   0.101   43.290
8     0.097   0.108   36.730
9     0.142   0.105   28.290
10    0.187   0.097   21.590
11    0.209   0.092   19.070
12    0.232   0.088   17.010
13    0.276   0.081   13.850
14    0.320   0.077   11.340
15    0.363   0.074   9.8600
16    0.385   0.073   9.2800
17    0.396   0.072   8.9800
18    0.407   0.071   8.6900
19    0.421   0.070   8.3000
20    0.428   0.070   8.1000
21    0.435   0.070   7.9100

File 2 (f2.dat)

67.660
56.290
44.730
34.290
28.590
24.070
21.010
16.850
10.340
6.8600
5.2800
4.9800
4.6900
3.3000
2.1000
1.9100

I want to replace the third column in f1.dat with the column in file f2.dat. The output of f1.dat must look like;


    # Off---=0.210
# Angle=-2.3
# Br    L1--    L2--    L3---
6     0.047   67.66   44.660
7     0.062   56.29   43.290
8     0.097   44.73   36.730
9     0.142   34.29   28.290
10    0.187   28.59   21.590
11    0.209   24.07   19.070
12    0.232   21.01   17.010
13    0.276   16.85   13.850
14    0.320   10.34   11.340
15    0.363   6.860   9.8600
16    0.385   5.280   9.2800
17    0.396   4.980   8.9800
18    0.407   4.690   8.6900
19    0.421   3.300   8.3000
20    0.428   2.100   8.1000
21    0.435   1.910   7.9100

Thank you for your help.

回答1:

This one-liner solves your problem:

With header

awk '{ if (NR > 3) { getline f2 < "f2.dat"; print $1 FS $2 FS f2 FS $4 } else print $0 }' f1.dat

or (nicely formatted)

awk '{ if (NR > 3) { getline f2 < "f2.dat"; printf "%-5d %8.3f %8.3f %8.4f\n",$1,$2,f2,$4 } else print $0 }' f1.dat

Without header

awk 'NR > 3 { getline f2 < "f2.dat"; print $1 FS $2 FS f2 FS $4 }' f1.dat

You can use getline to read input from f2.dat file into f2 variable. Then print the fields from f1.dat and f2.dat in the desired order separated by the predefined field separator FS or nicely formatted using printf. Awk starts to read f2.dat file after the 3rd row of f1.dat.



标签: bash shell