Skip to content

copyclip: Copy Jupyter Notebook Cells to macOS Clipboard

The copyclip tool is a Bash script designed to extract and format the contents of a Jupyter Notebook (.ipynb) and copy it to the macOS clipboard using pbcopy. It parses notebook cells using Python and converts them to readable Markdown format, which is especially useful for sharing notebook content or documenting it outside of the Jupyter environment.


πŸ› οΈ Features

  • Parses .ipynb files using Python 3
  • Outputs Markdown-formatted content
  • Differentiates between code and markdown cells
  • Automatically copies the output to clipboard on macOS
  • Provides clear cell separation and visual structure

πŸ“¦ Dependencies

  • python3 (installed by default on macOS)
  • pbcopy (macOS utility for clipboard access)
  • A valid .ipynb file

πŸ“„ Script Source

copyclip
#!/bin/bash

# Check if a file was provided
if [ -z "$1" ]; then
    echo "Usage: ./nbcopy.sh <path_to_notebook.ipynb>"
    exit 1
fi

# Check if the file exists
if [ ! -f "$1" ]; then
    echo "Error: File '$1' not found."
    exit 1
fi

# Use Python to parse the JSON and format the output
# We use python3 as it is standard on modern macOS
python3 -c "
import sys, json

try:
    with open(sys.argv[1], 'r', encoding='utf-8') as f:
        nb = json.load(f)

    output = []

    for i, cell in enumerate(nb.get('cells', [])):
        cell_type = cell.get('cell_type', '')
        source = ''.join(cell.get('source', []))

        # Add a visual separator for clarity
        output.append(f'--- CELL {i+1} ({cell_type.upper()}) ---')

        if cell_type == 'code':
            # Wrap code in markdown code blocks for better readability
            output.append(```'python')
            output.append(source)
            output.append(```')
        else:
            # Markdown cells are added as-is
            output.append(source)

        output.append('\\n')

    # Print to stdout so bash can pipe it
    print('\\n'.join(output))

except Exception as e:
    sys.stderr.write(f'Error processing notebook: {e}\\n')
    sys.exit(1)
" "$1" | pbcopy

# Check exit status of the pipe
if [ $? -eq 0 ]; then
    echo "βœ… Successfully extracted '$1' and copied to clipboard."
else
    echo "❌ Failed to copy to clipboard."
fi

βœ… Example Usage

./copyclip path/to/notebook.ipynb

This will extract the cells from the specified notebook and copy the Markdown-formatted result directly to your clipboard.


πŸ§ͺ Sample Output Format (Copied)

--- CELL 1 (MARKDOWN) ---
# My Notebook

--- CELL 2 (CODE) ---
´´´python
print("Hello, world!")
´´´

--- CELL 3 (MARKDOWN) ---
This is an explanation.