Jacek
Jacek

Reputation: 765

How to replace ith row's jth column with value from variable in bash

I have a file that looks like this:

6 6 1
0 0 0
0.0 0.0 0.0

2.938947259546411 -5.090405972278119 0.000000000000000

and I want to replace the first row's first column with value from var1 and first row's second column with value from var2

The values of the numbers can change; furthermore, there are repeated values in the first row, so I cannot use things like sed -i "s/6/$var1/"file

Is there a way for me to modify the file to

3 2 1
0 0 0
0.0 0.0 0.0

2.938947259546411 -5.090405972278119 0.000000000000000

by letting var1 be 3 and var2 be 2?

Upvotes: 2

Views: 82

Answers (1)

anubhava
anubhava

Reputation: 786136

awk can handle this easily:

var1='3'
var2='2'
awk -v c1="$var1" -v c2="$var2" 'NR==1{$1=c1; $2=c2} 1' file

3 2 1
0 0 0
0.0 0.0 0.0

2.938947259546411 -5.090405972278119 0.000000000000000

Upvotes: 5

Related Questions