Topic on Manual talk:Pywikibot

How to do a string replacement?

6
Summary by Marbot

Solution: The text must match exactly, including whitespace etc.

Marbot (talkcontribs)

I would like to replace {{MyFirstTemplate|field1=MyText|field2=MyText}} with {{MySecondTemplate|field3=MyNewText}}. According to the docu this should be the line:

python3 pwb.py replace -page:My_Page "{{MyFirstTemplate|field1=MyText|field2=MyText}}" "{{MySecondTemplate|field3=MyNewText}}" -summary:Awesome_replacement

However, nothing is replaced. The script tells that nothing to replace was found. I am a bit fuzzy what to enter. Any help appreciated.

Marbot (talkcontribs)

I guess it has somehting to do with the pipes but adding a \ in front of them does not help either.

Matěj Suchánek (talkcontribs)

Check for spelling mistakes and that you are connecting to the correct wiki. Note that the text must match exactly, including whitespace etc. Otherwise you will need to make a regex (and use -regex). The regex will then need the slashes to escape the pipes and other characters.

Marbot (talkcontribs)

Thanks for your response. This contained the decisive hint: Check the whitespace! I had {{MyFirstTemplate|field1=My Text|field2=My Text}} but wanted to replace {{MyFirstTemplate|field1=My_Text|field2=My_Text}}. The other paramteres understandably require _ though this does not which is understandable, too. Thanks a lot for helping me out of my misery! Much apprechiated.

Xqt (talkcontribs)

Works for me as expected:

C:\pwb\GIT\core>pwb replace -page:MyPage "{{MyFirstTemplate|field1=MyText|field2=MyText}}" "{{MySecondTemplate|field3=MyNewText}}" -site:wikipedia:test -simulate
 
The summary message for the command line replacements will be something like: 
Bot: Automated text replacement  (-{{MyFirstTemplate|field1=MyText|field2=MyText}} +{{MySecondTemplate|field3=MyNewText}}) 
Press Enter to use this automatic message, or enter a description of the changes your bot will make: Retrieving 1 pages from wikipedia:test.

>>> MyPage <<< @@ -6 +6 @@ - {{MyFirstTemplate|field1=MyText|field2=MyText}} + {{MySecondTemplate|field3=MyNewText}}

Do you want to accept these changes? ([y]es, [N]o, [e]dit original, edit [l]atest, open in [b]rowser, [m]ore context, [a]ll, [q]uit):

Note: There is no -regex option activated and the source string must match the text, see https://test.wikipedia.org/w/index.php?title=MyPage&action=edit

Marbot (talkcontribs)

Thank you for confirming! I know what I did wrong. See my answer to Matěj!