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

Creating a loop after a break using Markov Chain in Tikz

What happens when a metallic dragon and a chromatic dragon mate?

Why do UK politicians seemingly ignore opinion polls on Brexit?

I see my dog run

"My colleague's body is amazing"

How would photo IDs work for shapeshifters?

Why do we use polarized capacitors?

Is every set a filtered colimit of finite sets?

Shall I use personal or official e-mail account when registering to external websites for work purpose?

How to deal with fear of taking dependencies

Pristine Bit Checking

How do I create uniquely male characters?

Does a dangling wire really electrocute me if I'm standing in water?

Ideas for 3rd eye abilities

Is there a familial term for apples and pears?

Does the average primeness of natural numbers tend to zero?

New order #4: World

Doomsday-clock for my fantasy planet

Is there a way to make member function NOT callable from constructor?

Can I find out the caloric content of bread by dehydrating it?

LWC and complex parameters

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

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

How can I add custom success page



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

                    Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

                    Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

                    What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company