Hello everybody please help me to write a script to do the below please:

  1. I want to open a text file named C60_GRM_box.gro (I copied the first lines from this file below) and then extract the second line which is 127240 below;
GRM in vacuum
    1GRM     C1    1   0.061   0.071   0.000
    1GRM     C2    2   0.184   0.142   0.000
  1. Then, I want to subtract 2800 from the number extracted in step one and then divide the result by 60

what I want to do: (the number extracted in step number 1 - 2800)/60 = result

  1. Finally I want to open another txt file named C60_GRM_box.top (I have copied below all the data in the text file I want to replace part of it) and replace a number (which is the number beside the word G8LE, which is 3000 below) with the result I obtained in step 2, I have pasted all the content of the second file named C60_GRM_box.top below;
; Include forcefield parameters
include "/home/abdelaal/Desktop/GROMACS/C60:TAPC/C60_GRM/41/gromos54a7.ff/forcefield.itp"

; Include topology for GRM
include "/home/abdelaal/Desktop/GROMACS/C60:TAPC/C60_GRM/41/GRM.itp"
ifdef POSRES
include "/home/abdelaal/Desktop/GROMACS/C60:TAPC/C60_GRM/41/posrestr.itp"

; Include topology for C60
include "/home/abdelaal/Desktop/GROMACS/C60:TAPC/C60_GRM/41/C60.itp"

[ system ]

; Name

GRM in vacuum 

[ molecules ]

; Compound                 #mols

GRM                           1

G8LE                     strong text    3000

I don't need to open the files in steps 1 and 3, if I can do all the above without opening the files that would be perfect.

Many thanks

1 Answer 1


this bash shell script does what you want, but you can tweak it to change the source/target features.

assuming source.txt contains the source data; target.txt is the one that you want to replace

# get the 2nd line or source.txt-2800
val=$(expr `head -2 source.txt | tail -1` - 2800)
export val2=$(expr $val / 60)
# replace the result
perl -pi -e 's/(G8LE\s+[^\d]*)\d+/$1$ENV{val2}/g' target.txt
  • I created a text file named trial2.txt and pasted inside it the below: #!/bin/bash val=$(expr head -2 C60_GRM_box.gro | tail -1 - 2800) export val2=$(expr $val / 60) perl -pi -e 's/(G8LE\s+[^\d]*)\d+/$1$ENV{val2}/g' C60_GRM_box.top and then I opened a terminal and I wrote: bash trial2.txt but nothing happened, what is wrong please in what I have done ? Commented Apr 6, 2020 at 1:09
  • Thank you so much it worked :) Many thankssssssss for your effort:) Commented Apr 6, 2020 at 1:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .