Search and Replace text in All Fields in QGIS 3Search Shapefile and return ExtentsDelete all fields with the string “RAWI” using QGIS PythonHow to replace QGIS featureAtId() with getfeatures()?How to iterate through all fields, and all records in each field with GDAL/OGRQGIS Python Postcode Search ErrorCreating and manipulating an HTML frame in QGIS 3.2.0 Print Composer using PyQGISPython Scripting in QGIS to add features and select them?Python QGIS 2.18 to QGIS 3 : Shp file attribute joins and how do i specify the join fields?Adding processed features and layer to QGIS 3 projectQGIS Processing Script to Create and Add CSV Layer

Einstein metrics on spheres

Are white and non-white police officers equally likely to kill black suspects?

I see my dog run

Is domain driven design an anti-SQL pattern?

Can I legally use front facing blue light in the UK?

Lied on resume at previous job

Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?

When blogging recipes, how can I support both readers who want the narrative/journey and ones who want the printer-friendly recipe?

Was there ever an axiom rendered a theorem?

Unbreakable Formation vs. Cry of the Carnarium

What does 'script /dev/null' do?

Why is making salt water prohibited on Shabbat?

What is the command to reset a PC without deleting any files

Is there a familial term for apples and pears?

Calculate Levenshtein distance between two strings in Python

Are cabin dividers used to "hide" the flex of the airplane?

How can I add custom success page

Ideas for colorfully and clearly highlighting graph edges according to weights

Why is the design of haulage companies so “special”?

What is GPS' 19 year rollover and does it present a cybersecurity issue?

Some basic questions on halt and move in Turing machines

If a centaur druid Wild Shapes into a Giant Elk, do their Charge features stack?

What is the meaning of "of trouble" in the following sentence?

Why was the "bread communication" in the arena of Catching Fire left out in the movie?



Search and Replace text in All Fields in QGIS 3


Search Shapefile and return ExtentsDelete all fields with the string “RAWI” using QGIS PythonHow to replace QGIS featureAtId() with getfeatures()?How to iterate through all fields, and all records in each field with GDAL/OGRQGIS Python Postcode Search ErrorCreating and manipulating an HTML frame in QGIS 3.2.0 Print Composer using PyQGISPython Scripting in QGIS to add features and select them?Python QGIS 2.18 to QGIS 3 : Shp file attribute joins and how do i specify the join fields?Adding processed features and layer to QGIS 3 projectQGIS Processing Script to Create and Add CSV Layer






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I want to replace a string in ALL FIELDS / Columns of table without having to do it using field calculator in every field manually using replace( "RoadName1" ,'Wharf','WharfXXX').



I have



layer = iface.activeLayer()
searchText = "Wharf"
replaceText = "WharfXXX"
for field in layer.fields():
fieldName=field.name()
print (fieldName)
for feature in layer.getFeatures():
inText=str(feature[fieldName])
#print (inText)
if searchText in inText:
#try QgsStringReplacement
QgsStringReplacement(inText,replaceText, False, False)
#try Field Calculator

print ("Replaced %s with %s" %(inText,replaceText))
else:
#print ("not found")
pass


It seems to work but I am not seeing any changes in the dataset.



I can't find any example implementations of https://qgis.org/api/classQgsStringReplacement.htmlenter image description here



Does this function do what I think it's supposed to -i.e. replace text when it matches?



I guess I could configure field calc to use these inputs but the function above seems cleaner in the long run.



processing.run("qgis:fieldcalculator", 'INPUT':'test.tab)









share|improve this question






























    2















    I want to replace a string in ALL FIELDS / Columns of table without having to do it using field calculator in every field manually using replace( "RoadName1" ,'Wharf','WharfXXX').



    I have



    layer = iface.activeLayer()
    searchText = "Wharf"
    replaceText = "WharfXXX"
    for field in layer.fields():
    fieldName=field.name()
    print (fieldName)
    for feature in layer.getFeatures():
    inText=str(feature[fieldName])
    #print (inText)
    if searchText in inText:
    #try QgsStringReplacement
    QgsStringReplacement(inText,replaceText, False, False)
    #try Field Calculator

    print ("Replaced %s with %s" %(inText,replaceText))
    else:
    #print ("not found")
    pass


    It seems to work but I am not seeing any changes in the dataset.



    I can't find any example implementations of https://qgis.org/api/classQgsStringReplacement.htmlenter image description here



    Does this function do what I think it's supposed to -i.e. replace text when it matches?



    I guess I could configure field calc to use these inputs but the function above seems cleaner in the long run.



    processing.run("qgis:fieldcalculator", 'INPUT':'test.tab)









    share|improve this question


























      2












      2








      2








      I want to replace a string in ALL FIELDS / Columns of table without having to do it using field calculator in every field manually using replace( "RoadName1" ,'Wharf','WharfXXX').



      I have



      layer = iface.activeLayer()
      searchText = "Wharf"
      replaceText = "WharfXXX"
      for field in layer.fields():
      fieldName=field.name()
      print (fieldName)
      for feature in layer.getFeatures():
      inText=str(feature[fieldName])
      #print (inText)
      if searchText in inText:
      #try QgsStringReplacement
      QgsStringReplacement(inText,replaceText, False, False)
      #try Field Calculator

      print ("Replaced %s with %s" %(inText,replaceText))
      else:
      #print ("not found")
      pass


      It seems to work but I am not seeing any changes in the dataset.



      I can't find any example implementations of https://qgis.org/api/classQgsStringReplacement.htmlenter image description here



      Does this function do what I think it's supposed to -i.e. replace text when it matches?



      I guess I could configure field calc to use these inputs but the function above seems cleaner in the long run.



      processing.run("qgis:fieldcalculator", 'INPUT':'test.tab)









      share|improve this question
















      I want to replace a string in ALL FIELDS / Columns of table without having to do it using field calculator in every field manually using replace( "RoadName1" ,'Wharf','WharfXXX').



      I have



      layer = iface.activeLayer()
      searchText = "Wharf"
      replaceText = "WharfXXX"
      for field in layer.fields():
      fieldName=field.name()
      print (fieldName)
      for feature in layer.getFeatures():
      inText=str(feature[fieldName])
      #print (inText)
      if searchText in inText:
      #try QgsStringReplacement
      QgsStringReplacement(inText,replaceText, False, False)
      #try Field Calculator

      print ("Replaced %s with %s" %(inText,replaceText))
      else:
      #print ("not found")
      pass


      It seems to work but I am not seeing any changes in the dataset.



      I can't find any example implementations of https://qgis.org/api/classQgsStringReplacement.htmlenter image description here



      Does this function do what I think it's supposed to -i.e. replace text when it matches?



      I guess I could configure field calc to use these inputs but the function above seems cleaner in the long run.



      processing.run("qgis:fieldcalculator", 'INPUT':'test.tab)






      pyqgis pyqgis-3 qgsstringreplacement






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 5 at 6:14









      Kadir Şahbaz

      4,60221531




      4,60221531










      asked Apr 5 at 2:21









      GeorgeCGeorgeC

      2,90132981




      2,90132981




















          2 Answers
          2






          active

          oldest

          votes


















          4














          You can try code below (backup data prior):



          layer = iface.activeLayer()
          textfields = [f.name() for f in layer.fields() if f.typeName()=='String']

          replacedict = 'Hus,':'HusXYZ,','1':'ONE'

          with edit(layer):
          for feature in layer.getFeatures():
          for f in textfields:
          value = feature[f]
          if type(value)== str:
          new_value = ' '.join([replacedict[word] if word in replacedict else word for word in value.split()])
          _=feature.setAttribute(feature.fieldNameIndex(f), new_value)
          _=layer.updateFeature(feature)


          From:
          enter image description here



          To:
          enter image description here






          share|improve this answer

























          • very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?

            – GeorgeC
            Apr 5 at 19:54


















          3














          You can solve your problem using layer.changeAttributeValue() in an edit session.



          layer = iface.activeLayer()
          searchText = "Wharf"
          replaceText = "WharfXXX"

          # Start edit session for the layer
          layer.startEditing()

          for field in layer.fields():
          fieldName = field.name()
          # get field index
          fieldIndex = layer.fields().indexFromName(fieldName)

          for feature in layer.getFeatures():
          inText = str(feature[fieldName])

          if searchText in inText:
          # change inText
          outText = inText.replace(searchText, replaceText)
          # change field value of the attribute (in memory)
          layer.changeAttributeValue(feature.id(), fieldIndex, outText)

          # save changes
          layer.commitChanges()



          Or you can use layer.dataProvider().changeAttributeValues(). In that case, you can change multiple fields at once. To see changes you may need to reopen the attribute table.



          layer = iface.activeLayer()
          searchText = "Wharf"
          replaceText = "WharfXXX"

          # get data provider
          dpr = layer.dataProvider()

          for field in layer.fields():
          fieldName=field.name()

          for feature in layer.getFeatures():
          inText = str(feature[fieldName])
          # get field index
          fieldIndex = layer.fields().indexFromName(fieldName)

          if searchText in inText:
          # change inText
          outText = inText.replace(searchText, replaceText)
          # save changes
          dpr.changeAttributeValues(feature.id(): fieldIndex: outText)





          share|improve this answer























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "79"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f317855%2fsearch-and-replace-text-in-all-fields-in-qgis-3%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4














            You can try code below (backup data prior):



            layer = iface.activeLayer()
            textfields = [f.name() for f in layer.fields() if f.typeName()=='String']

            replacedict = 'Hus,':'HusXYZ,','1':'ONE'

            with edit(layer):
            for feature in layer.getFeatures():
            for f in textfields:
            value = feature[f]
            if type(value)== str:
            new_value = ' '.join([replacedict[word] if word in replacedict else word for word in value.split()])
            _=feature.setAttribute(feature.fieldNameIndex(f), new_value)
            _=layer.updateFeature(feature)


            From:
            enter image description here



            To:
            enter image description here






            share|improve this answer

























            • very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?

              – GeorgeC
              Apr 5 at 19:54















            4














            You can try code below (backup data prior):



            layer = iface.activeLayer()
            textfields = [f.name() for f in layer.fields() if f.typeName()=='String']

            replacedict = 'Hus,':'HusXYZ,','1':'ONE'

            with edit(layer):
            for feature in layer.getFeatures():
            for f in textfields:
            value = feature[f]
            if type(value)== str:
            new_value = ' '.join([replacedict[word] if word in replacedict else word for word in value.split()])
            _=feature.setAttribute(feature.fieldNameIndex(f), new_value)
            _=layer.updateFeature(feature)


            From:
            enter image description here



            To:
            enter image description here






            share|improve this answer

























            • very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?

              – GeorgeC
              Apr 5 at 19:54













            4












            4








            4







            You can try code below (backup data prior):



            layer = iface.activeLayer()
            textfields = [f.name() for f in layer.fields() if f.typeName()=='String']

            replacedict = 'Hus,':'HusXYZ,','1':'ONE'

            with edit(layer):
            for feature in layer.getFeatures():
            for f in textfields:
            value = feature[f]
            if type(value)== str:
            new_value = ' '.join([replacedict[word] if word in replacedict else word for word in value.split()])
            _=feature.setAttribute(feature.fieldNameIndex(f), new_value)
            _=layer.updateFeature(feature)


            From:
            enter image description here



            To:
            enter image description here






            share|improve this answer















            You can try code below (backup data prior):



            layer = iface.activeLayer()
            textfields = [f.name() for f in layer.fields() if f.typeName()=='String']

            replacedict = 'Hus,':'HusXYZ,','1':'ONE'

            with edit(layer):
            for feature in layer.getFeatures():
            for f in textfields:
            value = feature[f]
            if type(value)== str:
            new_value = ' '.join([replacedict[word] if word in replacedict else word for word in value.split()])
            _=feature.setAttribute(feature.fieldNameIndex(f), new_value)
            _=layer.updateFeature(feature)


            From:
            enter image description here



            To:
            enter image description here







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 5 at 7:00

























            answered Apr 5 at 6:24









            BERABERA

            17k62044




            17k62044












            • very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?

              – GeorgeC
              Apr 5 at 19:54

















            • very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?

              – GeorgeC
              Apr 5 at 19:54
















            very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?

            – GeorgeC
            Apr 5 at 19:54





            very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?

            – GeorgeC
            Apr 5 at 19:54













            3














            You can solve your problem using layer.changeAttributeValue() in an edit session.



            layer = iface.activeLayer()
            searchText = "Wharf"
            replaceText = "WharfXXX"

            # Start edit session for the layer
            layer.startEditing()

            for field in layer.fields():
            fieldName = field.name()
            # get field index
            fieldIndex = layer.fields().indexFromName(fieldName)

            for feature in layer.getFeatures():
            inText = str(feature[fieldName])

            if searchText in inText:
            # change inText
            outText = inText.replace(searchText, replaceText)
            # change field value of the attribute (in memory)
            layer.changeAttributeValue(feature.id(), fieldIndex, outText)

            # save changes
            layer.commitChanges()



            Or you can use layer.dataProvider().changeAttributeValues(). In that case, you can change multiple fields at once. To see changes you may need to reopen the attribute table.



            layer = iface.activeLayer()
            searchText = "Wharf"
            replaceText = "WharfXXX"

            # get data provider
            dpr = layer.dataProvider()

            for field in layer.fields():
            fieldName=field.name()

            for feature in layer.getFeatures():
            inText = str(feature[fieldName])
            # get field index
            fieldIndex = layer.fields().indexFromName(fieldName)

            if searchText in inText:
            # change inText
            outText = inText.replace(searchText, replaceText)
            # save changes
            dpr.changeAttributeValues(feature.id(): fieldIndex: outText)





            share|improve this answer



























              3














              You can solve your problem using layer.changeAttributeValue() in an edit session.



              layer = iface.activeLayer()
              searchText = "Wharf"
              replaceText = "WharfXXX"

              # Start edit session for the layer
              layer.startEditing()

              for field in layer.fields():
              fieldName = field.name()
              # get field index
              fieldIndex = layer.fields().indexFromName(fieldName)

              for feature in layer.getFeatures():
              inText = str(feature[fieldName])

              if searchText in inText:
              # change inText
              outText = inText.replace(searchText, replaceText)
              # change field value of the attribute (in memory)
              layer.changeAttributeValue(feature.id(), fieldIndex, outText)

              # save changes
              layer.commitChanges()



              Or you can use layer.dataProvider().changeAttributeValues(). In that case, you can change multiple fields at once. To see changes you may need to reopen the attribute table.



              layer = iface.activeLayer()
              searchText = "Wharf"
              replaceText = "WharfXXX"

              # get data provider
              dpr = layer.dataProvider()

              for field in layer.fields():
              fieldName=field.name()

              for feature in layer.getFeatures():
              inText = str(feature[fieldName])
              # get field index
              fieldIndex = layer.fields().indexFromName(fieldName)

              if searchText in inText:
              # change inText
              outText = inText.replace(searchText, replaceText)
              # save changes
              dpr.changeAttributeValues(feature.id(): fieldIndex: outText)





              share|improve this answer

























                3












                3








                3







                You can solve your problem using layer.changeAttributeValue() in an edit session.



                layer = iface.activeLayer()
                searchText = "Wharf"
                replaceText = "WharfXXX"

                # Start edit session for the layer
                layer.startEditing()

                for field in layer.fields():
                fieldName = field.name()
                # get field index
                fieldIndex = layer.fields().indexFromName(fieldName)

                for feature in layer.getFeatures():
                inText = str(feature[fieldName])

                if searchText in inText:
                # change inText
                outText = inText.replace(searchText, replaceText)
                # change field value of the attribute (in memory)
                layer.changeAttributeValue(feature.id(), fieldIndex, outText)

                # save changes
                layer.commitChanges()



                Or you can use layer.dataProvider().changeAttributeValues(). In that case, you can change multiple fields at once. To see changes you may need to reopen the attribute table.



                layer = iface.activeLayer()
                searchText = "Wharf"
                replaceText = "WharfXXX"

                # get data provider
                dpr = layer.dataProvider()

                for field in layer.fields():
                fieldName=field.name()

                for feature in layer.getFeatures():
                inText = str(feature[fieldName])
                # get field index
                fieldIndex = layer.fields().indexFromName(fieldName)

                if searchText in inText:
                # change inText
                outText = inText.replace(searchText, replaceText)
                # save changes
                dpr.changeAttributeValues(feature.id(): fieldIndex: outText)





                share|improve this answer













                You can solve your problem using layer.changeAttributeValue() in an edit session.



                layer = iface.activeLayer()
                searchText = "Wharf"
                replaceText = "WharfXXX"

                # Start edit session for the layer
                layer.startEditing()

                for field in layer.fields():
                fieldName = field.name()
                # get field index
                fieldIndex = layer.fields().indexFromName(fieldName)

                for feature in layer.getFeatures():
                inText = str(feature[fieldName])

                if searchText in inText:
                # change inText
                outText = inText.replace(searchText, replaceText)
                # change field value of the attribute (in memory)
                layer.changeAttributeValue(feature.id(), fieldIndex, outText)

                # save changes
                layer.commitChanges()



                Or you can use layer.dataProvider().changeAttributeValues(). In that case, you can change multiple fields at once. To see changes you may need to reopen the attribute table.



                layer = iface.activeLayer()
                searchText = "Wharf"
                replaceText = "WharfXXX"

                # get data provider
                dpr = layer.dataProvider()

                for field in layer.fields():
                fieldName=field.name()

                for feature in layer.getFeatures():
                inText = str(feature[fieldName])
                # get field index
                fieldIndex = layer.fields().indexFromName(fieldName)

                if searchText in inText:
                # change inText
                outText = inText.replace(searchText, replaceText)
                # save changes
                dpr.changeAttributeValues(feature.id(): fieldIndex: outText)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 5 at 6:12









                Kadir ŞahbazKadir Şahbaz

                4,60221531




                4,60221531



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f317855%2fsearch-and-replace-text-in-all-fields-in-qgis-3%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Sum ergo cogito? 1 nng

                    419 nièngy_Soadمي 19bal1.5o_g

                    Queiggey Chernihivv 9NnOo i Zw X QqKk LpB