0

I have a text file which has 4 columns with 300 lines. I want to add 5th columns where 1st hundred lines will be multiplication of 1*0.02, 2*0.02... and from hundred one lines 2.2, 2.4 ...

0.02 
0.04
.
.
.
2           (in 100 lines)
2.2
2.4
.
.
.
12           (in 300 lines)

my text file:

# "Frame" "Timestep" "WignerSeitz.interstitial_count" "WignerSeitz.vacancy_count"
0 0 0 0 
1 100 0 0 
2 200 0 0 
3 300 0 0 
.
.
98 9800 16 16 
99 9900 16 16 
100 10000 15 15
.
.
299 29900 48 48 
300 30000 55 55

expected output:

# "Frame" "Timestep" "WignerSeitz.interstitial_count" "WignerSeitz.vacancy_count"
0 0 0 0 0
1 100 0 0 0.02 
2 200 0 0 0.04
3 300 0 0 0.06
.
.
98 9800 16 16 1.96
99 9900 16 16 1.98
100 10000 15 15 2
.
.
299 29900 48 48 11.8 
300 30000 55 55 12 
0
0

supposing you mean after 100, you need to add 0.2 to each record after, Using awk you can do something like following code:

awk -v x=2 '{if($1<101){print $0 FS ($1*0.02)}else{x=x+0.2; print $0 FS x}}' file.txt

where:

-v used to let awk know that your are using variable x with initial value 2

$1<101 to let your first part of the code work as long as the first column is less than 101

FS is static variable in awk that contain the field separator of your file.

Then you can adjust your step as per your requirement.

1
  • You are amazing. it is working fine. Thank you very much.
    – Alex
    Feb 12 '20 at 21:06
0

From what I understand you want 5th column, calculated bu multiply 1st to 0.2

This can be done with awk for example:

 gawk '{printf "%s %.2f\n", $0,$1*0.02}'
0

There is a discrepancy between your spec and the sample output: from line 101 till 300 you want a step size of 0.2 but end theb last line with 12 - can't be. 200 steps of 0.2 will yield "40" - that will make 42 for the last line's $5 entry. Should that be true, try

$ awk '{print $0, ($1>100)*-18+$1*.02*(1+($1>100)*9)}' file
0 0 0 0  0
1 100 0 0  0.02
2 200 0 0  0.04
3 300 0 0  0.06
. 0
. 0
98 9800 16 16  1.96
99 9900 16 16  1.98
100 10000 15 15 2
101 10100 15 15 2.2
102 10200 15 15 2.4
. 0
199 19900 15 15 21.8
200 20000 15 15 22
201 20100 15 15 22.2
. 0
299 29900 48 48  41.8
300 30000 55 55 42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.