Skip to main content
Example scripts
arrow icon
To homepage
Confluence
Cloud icon
Cloud

Find and Replace Text Across Space

Tags
Created 1 year ago, Updated 1 day(s) ago
App in script
ScriptRunner For Confluence
ScriptRunner For Confluence
by Adaptavist
Compatibility
compatibility bullet
Confluence
Language |
groovy
def spaceKey = 'TS'
def spaceInfo = get("/wiki/api/v2/spaces?keys=${spaceKey}").asObject(Map).body

if (!spaceInfo.results && spaceInfo.results.size() == 0) {
    logger.info("Space with space key: ${spaceKey} doesn't exist")
    return
}

def rest = "/wiki/api/v2/spaces/${spaceInfo.results[0].id}/pages?body-format=storage"

def replaceText(rest) {
    def oldText = 'test'
    def newText = 'page'

    def pages = get(rest)
            .asObject(Map)
            .body
            .results

    pages.each { page ->
        def storage = page.body.storage.value
        def newContent = storage.replace(oldText, newText)
        def currentVersion = page.version.number

        if (newContent == storage) {
            return
        }

        put("/wiki/api/v2/pages/${page.id}")
                .header("Content-Type", "application/json")
                .body([
                        id: page.id,
                        status: "current",
                        title: page.title,
                        body: [
                                representation: "storage",
                                value: newContent
                        ],
                        version: [
                                number: currentVersion + 1
                        ],
                ])
                .asObject(Map)

        logger.info("Page '${page.title}' has been updated.")
    }

    def next = get(rest).asObject(Map).body._links.next

    if (next) {
        replaceText(next)
    } else {
        return
    }
}

replaceText(rest)
Having an issue with this script?
Report it here