2
$\begingroup$

I need to delete all duplicate cells in my notebook, keeping just one occurrence of each pair (or tuple). No need to choose which to keep. Is there a (simple) way to do it?

$\endgroup$
3
  • $\begingroup$ Are they exact duplicates by the structure (Ctrl+Shit+E)? How did it happen? $\endgroup$
    – Kuba
    Commented Jul 15, 2016 at 18:25
  • $\begingroup$ I'm not sure I understand your question. If the cells are "duplicates" of eachother, why do you need to choose which one you keep? You could realize this by importing the notebook as "notebook expression" and do a simple expression replacement. $\endgroup$
    – halirutan
    Commented Jul 15, 2016 at 18:37
  • $\begingroup$ @halirutan The notebook has a lot of cells (10000+). Some (few hundreds) have one or two duplicate (just some of them). I cannot do the replacement by hand as they are too many. I need to preserve just one single copy of each. Is there a hack to do it programmatically? I mean, how could I scan the cells and keep track of duplicates? $\endgroup$
    – JavierG
    Commented Jul 15, 2016 at 23:18

1 Answer 1

4
$\begingroup$

You may use the Low-Level Notebook Programming guide.

Create a notebook with CreateDocument for the example that has duplicate cells.

SeedRandom[123];
nb = CreateDocument[Table[ExpressionCell[n, "Input"], {n, RandomInteger[{1, 5}, 20]}]]

The Cells can be GatherBy'ed their NotebookRead representation. They will have different CellChangeTimes so this is made to be the same for all cells. The first of each gathered sublist is kept and the Rest are NotebookDelete'ed from the notebook.

NotebookDelete@
 Flatten[Rest /@ 
   GatherBy[Cells[nb], 
    NotebookRead[#] /. {HoldPattern[CellChangeTimes -> _] -> Nothing} &]
  ]

The duplicate cells are now deleted. For the cases where there are no duplicates then they will form a sublist with a single cell. This cell will be removed by Rest so that it is not deleted.

If running this in the notebook you want to clean-up then replace Cells[nb] with Cells[] to get the cells in the current notebook.

The cells have to be identical in their NotebookRead form for this to work.

Hope this helps.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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