Message Boards Message Boards

1
|
3320 Views
|
4 Replies
|
4 Total Likes
View groups...
Share
Share this post:

[?] Edit and evaluate several scripts automatically?

Posted 6 years ago

Hello, I have written many Mathematica scripts for images I need to edit. Now I found out that there is an error in all of them. I need to replace some lines of code in all of them and evaluate all notebooks again. Is there a way to do this automatically?

Thank you!

POSTED BY: Nik Ka
4 Replies

You should use the Notebook handling commands in MMA: The documentation is here

You have several options. You can open the notebooks programmatically and use the selection commands in the tutorial above to find and change text. Alternatively, you can do some string manipulation on the input cells of the notebooks. This is a sample of the second approach:

First get your files and set a new destination: (this example is on a Mac but its the same on a PC with different path specifications)

files = FileNames["/Users/xxx/Desktop/ToProcess/*.nb"]
newpath = "/Users/xxx/Desktop/Processed/"

Next, change the text in the files in bulk: (in this example, I changed ArcSin to ArcCos -- you can do whatever you want but realize the input cells were brought in and converted to strings by my code)

Map[Export[newpath<>FileNameTake[#],Notebook[StringReplace[NotebookImport[#,"Input"->"InputText"],"ArcSin"->"ArcCos"]]]&,files]

Now evaluate the new files in bulk:

filesToEval = FileNames[newpath <> "*.nb"]
evalNotebook[name_] := 
 Module[{nb}, nb = NotebookOpen[name]; 
  NotebookEvaluate[nb, InsertResults -> True];
  NotebookSave[nb]; NotebookClose[nb]]
Map[evalNotebook, filesToEval]

Since you gave no example, I am assuming that you can do this with simple text manipulation. If not, you may have to explore some of the other ways to import the notebook cells. You can keep them as expressions and use replace rules and pattern matchings. You can also use the selection commands to find and change things. I hope this will get you started. Please let me know what approach you finally decide to use.

Regards

Neil

POSTED BY: Neil Singer
Posted 6 years ago

Thank you very much! I have used the second approach, you have saved me a lot of time.

POSTED BY: Nik Ka

Use find/replace in the edit menu->find...

POSTED BY: Neil Singer
Posted 6 years ago

The Problem is that there are really many of them, i do not want to do it by hand (find). The evaluation of one scripts needs a minute, I dont want to evaluate a script, wait a minute, evaluate again etc.

POSTED BY: Nik Ka
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract