7

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!

1
  • Have you tried to manipulate the table with other external program to edit the attribute table? (openoffice for example). Nov 13, 2014 at 11:33

1 Answer 1

11

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)
2
  • 1
    the simple replace function will work just as fine for this use case.
    – underdark
    Nov 15, 2014 at 19:22
  • @underdark - Indeed it does!
    – Joseph
    Mar 16, 2016 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.