Counting number of layers returned by g.list in GRASS GIS

I am running a script that is producing a very large number of layers. As it takes a while, I wanted to find out how many layers were already created using the command line. Trivial thing perhaps, but I wasn’t really sure how to do it. After a bit of search, one way I found uses the versatile awk command line tool.

In the code below the g.list function is used to list all layers in the mapset VECEA. This is passed to (piped) as an array to awk, which splits the array and counts the elements.

echo `g.list type=raster pattern=* mapset=VECE sep=,` | awk '{n=split($0, array, ",")} END{print n}'

And the following will give the number of layers which name start with maxent in the mapset VECEA.

echo `g.list type=raster pattern=maxent* mapset=VECEA sep=,` | awk '{n=split($0, array, ",")} END{print n}'

I am sure there are other, and possibly better, ways, but this serves my purpose, and who knows, it may be useful for others.

3 thoughts on “Counting number of layers returned by g.list in GRASS GIS

  1. Pingback: Counting number of layers returned by g.list in GRASS GIS | GeoNe.ws

  2. Panos

    An alternative could be the following:

    “`
    python -c ‘import grass.script; maps = grass.script.parse_command(“g.list”, type=”raster”, pattern=”T*”, mapset=”corrected”); print(len(maps))’
    “`
    Admittedly it is more verbose, but python is easier to write/debug than awk (at least for python users :P)

    1. Thanks🙂. What makes it (for me) fairly easy to run/understand GRASS command in Python, like yours above, is that the grass.script interface is really much like the one provided by rgrass7 in R: This is for example how I would do it in R for example:

      library(rgrass7)
      length(execGRASS(“g.list”, type=”raster”, pattern=”T*”, mapset=”corrected”, intern=TRUE))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s