hamad khan
hamad khan

Reputation: 369

Replacing a specific column of a file with the column of another file using sed in linux

I have two files.

file1 has the data like belowing containing only one column.

112.319
108.915
105.512

file2 has the data like belowing containing eight columns.

0.000000     0.000     0.000     0.000     0.000         0     0.0001.0000E+20  
0.000000     0.000     0.000     0.000 20.000000         0     0.0001.0000E+20  
0.000000     0.000     0.000     0.000 20.000000         0     0.0001.0000E+20 

I want to replace the first column of file2 with the first column of file1 and the output would be

112.319     0.000     0.000     0.000     0.000         0     0.0001.0000E+20  
108.915     0.000     0.000     0.000 20.000000         0     0.0001.0000E+20  
105.512     0.000     0.000     0.000 20.000000         0     0.0001.0000E+20

I tried to replace the first record of each line with the first record of other line but was not successful. I would be thankful if somebody can help me doing is using sed.

best regards.

Upvotes: 1

Views: 3363

Answers (3)

potong
potong

Reputation: 58371

This might work for you:

 cut -d' ' -f2- file2 | paste -d' ' file1 -

or this (GNU sed):

sed 'R file2' file1 | sed 'N;s/\n\S*//'

or this:

 awk 'FNR==NR{a[NR]=$1;next};{sub($1,a[FNR])}1' file1 file2

EDIT:

This might work for you:(GNU sed?)

sed '=;s/.*/s|\\S*|&|/' file1 | sed 'N;s/\n//' | sed -i -f - file2

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246754

join -o 1.2,2.3,2.4,2.5,2.6,2.7,2.8 <(cat -n file1) <(cat -n file2) | column -t

produces

112.319  0.000  0.000  0.000  0.000      0  0.0001.0000E+20
108.915  0.000  0.000  0.000  20.000000  0  0.0001.0000E+20
105.512  0.000  0.000  0.000  20.000000  0  0.0001.0000E+20

Update: since the whitespace is significant, you can use string replacements. Here's awk:

awk 'NR==FNR {n[FNR]=$1; next} {sub(/[^[:space:]]+/, n[FNR]); print}' f1 f2

producing

112.319     0.000     0.000     0.000     0.000         0     0.0001.0000E+20
108.915     0.000     0.000     0.000 20.000000         0     0.0001.0000E+20
105.512     0.000     0.000     0.000 20.000000         0     0.0001.0000E+20

Upvotes: 1

kev
kev

Reputation: 161614

You can use the paste/tr/cut/column commands:

$ paste file{1,2} | tr -s ' ' | cut -d ' ' -f 1,3- | column -t
112.319  0.000000  0.000  0.000  0.000      0  0.0001.0000E+20
108.915  0.000000  0.000  0.000  20.000000  0  0.0001.0000E+20
105.512  0.000000  0.000  0.000  20.000000  0  0.0001.0000E+20

Upvotes: 2

Related Questions