-1

I'm working with bash via Ubuntu terminal. I want to make the same text edit to all the files in my directory that have the same extension. My directory contains several versions of 227 numerically counted data files. So for example I have:

tmp0001.ctl
tmp0001.out
tmp0001.trees
tmp0001.txt
tmp0002.ctl
tmp0002.out
tmp0002.trees
tmp002.txt

And so on.

The files I am interested in editing are those with the extension ".ctl". At present, .ctl files look like this (though the numbers vary from tmp0001 through 227 of course):

seqfile = tmp0001.txt
treefile = tmp0001.trees
outfile = tmp0001.out
noisy = 3
seqtype = 2
model = 0
aaRatefile = 
Small_Diff = 0.1e-6
getSE = 2
method = 1

I want to edit the .ctl files so that they read:

seqfile = tmp0001.txt
treefile = tmp0001.trees
outfile = tmp0001.out
noisy = 3
seqtype = 2
model = 2
aaRatefile = lg.dat
fix_alpha = 0
alpha = .5
ncatG = 4
Small_Diff = 0.1e-6
getSE = 2
method = 1

I'm not sure how to do this though, I would guess to use an editor like nano or sed, but I'm not sure how to automate this. I thought something along the lines of:

for file in *.ctl
do
nano
???

Hope this isn't too convoluted! Essentially I want to change two lines already in there (model and aaratefile), and add 2 more lines (>ix_alpha = 0 and alpha = .5) in each .ctl file.

Thanks!

choroba
  • 231,213
  • 25
  • 204
  • 289

1 Answers1

-1

You can use sed to perform the task:

sed -e 's/model = 0/model = 2/; s/aaRatefile = /aaRatefile = lg.dat/' \
    -e '/Small_Diff/ i fix_alpha = 0\nalpha = .5\nncatG = 4' \
    -i~ *.ctl
  • s/pattern/replacement/ replaces "pattern" by "replacement"
  • i text inserts the text
  • if a command is preceded by /pattern/, the command is run only when the current line matches the pattern, i.e. in this case, the lines are inserted before the Small_Diff line.
  • -i~ tells sed to replace the files "in place", leaving a backup with the ~ appended to the name (so there will be backups named tmp0001.ctl~ etc.)
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Hey thanks for responding. This works, but it only prints the edits to my terminal and doesn't actually change the files on my computer. How would I go about actually editing the files themselves? – Richie Howard Jul 16 '18 at 15:52
  • Do you mean the `-i` doesn't change the files in place? – choroba Jul 16 '18 at 16:24