[GIS] How to remove Commas from field values in multiple files

arcmapattribute-tablefields-attributesqgis

I'm working in QGIS, presenting data in ArcMap, and Arc is having trouble with the attribute tables.

I have a "species" column which lists the species found in that area and have added commas "," in this field to separate species. Arc can't handle the commas so I would like to replace these in QGIS simply with a space.

Is there an easy way to do this?

I have tried replace and regexp_replace but I'm either doing this wrong or it is just not the way to do it…

I have a large amount of files to work with so an easy fix to this would be welcomed!

Best Answer

You can use this command to replace all commas in the fields of your Species column with spaces:

regexp_replace( "Species", ',', ' ' )

In this post answered by Nathan, the regex_replace function is described by :

regexp_replace(string,regex,after)

So in your case:

  • 'string' is your column (species)
  • 'regex' is the character you want changed (comma)
  • 'after' is what you want the character to be replaced with (leave empty for a space or add a space between the qutotation marks to create 2 spaces in the result)

EDIT:

I noticed I didn't answer the question completely as it asked how to remove commas in multiple shapefiles. Therefore, if all shapefiles are loaded into QGIS, you can use the following code to iterate through each layer and replace all commas with spaces for a specific field:

field = "Species"
formula = """ replace( "Species", ',', ' ' ) """

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    idx = layer.fieldNameIndex( field )
    e = QgsExpression( formula )
    e.prepare( layer.pendingFields() )
    with edit(layer):
        for f in layer.getFeatures():
            f[idx] = e.evaluate(f)
            layer.updateFeature(f)
Related Question