awk - Bash: nested for loop to iterativly change a paritular element in a matrix -
i try change in file.txt formatted follow:
0.0 0.0 1.0 2.0 3.0 0.0 0.0 3.0 3.0 35.0 ...
only second zeros in each lines: 0.0 numbers.
i know sed
command change elements if write that:
input=0 f in {0..2} sed -i "1s/$input/$f/" file.txt input=$f done
the sed command change first 0 in file, changing to:
1.0 0.0 1.0 2.0 3.0 1.0 0.0 3.0 3.0 35.0 ...
but, instead, like:
0.0 0.1 1.0 2.0 3.0 0.0 0.1 3.0 3.0 35.0 ...
so how can specify sed
must change number?
upgrade:
i try use sed
command guessed sadasidha:
number=0.2 sed -r "s/^([0-9].[0-9]) ([0-9].[0-9])/\1 ${number}/" input.txt
but request bit different, idea make loop in can increment second element on fourth line, instance, 10 times, second element of third line, second line , first one...as in 4 loop as:
input=0 f in {0..10} m in {0..10} s in {0..10} g in {0..10} change second element on fourth line 10 times, input=$f done change second element on third line 10 times, input=$m done ....
so can have 11^4 different values of elements in second rows each combination of numbers put inside loop (i.e.: between 0,10).
this job awk
. default awk
splits of sequences of whitespaces ([[:space:]]+
). once awk
reads line, splits line on default delimiter , assigns them variables can referenced using $
, column number.
for example:
$ cat file 0.0 0.0 1.0 2.0 3.0 0.0 0.0 3.0 3.0 35.0
$ awk '{$2=($2==0?0.1:$2)}1' file 0.0 0.1 1.0 2.0 3.0 0.0 0.1 3.0 3.0 35.0
we increment value of second column using $2
, 1
@ end allows print line. can right as:
$ awk '{$2=($2==0?0.1:$2); print}' file 0.0 0.1 1.0 2.0 3.0 0.0 0.1 3.0 3.0 35.0
Comments
Post a Comment