Replace Word Snippet

Last modified by Thomas Mortagne on 2021/03/18 11:28

cogSearch for documents matching a word and replace the word with another word
TypeSnippet
Category
Developed by

Vincent Massol

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

Be very careful when using something like this on your whole wiki. It can have unexpected side effects (like replacing parts of words in place you didn't expect) and you'll have no quick way to rollback (you'll have to do it manually, page by page).

{{velocity}}
#set ($word = $request.word)
#set($replacement = $request.replacement)
#if ("$!word" == "" || "$!replacement" == "")
 To use this replacement tool you need to pass the "word" and "replacement" variables in the query string.
 For example: $request.getRequestURL().toString()?word=welcome&replacement=bienvenue
#else
  #if ($request.confirm == "1")
   The following documents have had the word "$word" replaced with "$replacement":
  #else
   The following documents contain the word "$word":
  #end
  #set ($xwql = "where doc.content like '%$word%' and doc.fullName <> '$doc.fullName'")
  #foreach ($item in $services.query.xwql($xwql).execute())
    #if ($request.confirm == "1")
      #set ($itemDoc = $xwiki.getDocument($item))
      #set ($discard = $itemDoc.setContent($itemDoc.getContent().replaceAll($word, $replacement)))
      #set ($discard = $itemDoc.save("Replaced '$word' by '$replacement'"))
     * [[$item>>$item]] replaced!
    #else
     * [[$item>>$item]]
    #end
  #end

  #if ($request.confirm != "1")
    [[Replace "$word" by "$replacement">>?confirm=1&word=$word&replacement=$replacement]]
  #end
#end
{{/velocity}}

Get Connected