Create attribute based on portion of a file name
I am struggling with what I think should be a fairly simple scripting task.
For a given file, I import the filename and directory using the following:
IMPORT FILENAME="%FNAME_W_DIR%"
The filenames I am importing all conform to the following format
Name_extra.shp
I would like to include all of the text preceding the underscore in an attribute, similar to as shown below
Attribute=Name
Would anyone be able to help me out?
Answers
-
Hi,
You might try something like the following script command, once you've loaded the file:
CALC_ATTR_FORMULA NEW_ATTR="NewAttr" FORMULA="clip( search( <Feature Layer Name>, '.*_' ), '', '_' )"
"NewAttr" is the name of the new attribute. Change it to something suitable to your use case.
The search() function returns the substring from the first parameter that matches the regular expression denoted by the second parameter. Both parameters must be strings. In this case, the first parameter is <Feature Layer Name>, which is a special attribute that resolves to the layer's name in the Control Center). The second parameter is '.*_', which means match any character up to '_'. In your case, this will return a string equivalent to "Name_".
That string is then passed to the clip() function as its first parameter. The clip function() removes anything matching the second parameter from the front of the first parameter and anything matching the third parameter from whatever remains of the first parameter. In this case, the second parameter does nothing, '', the empty string, the third parameter from the end of the string, '_' causes the trailing '_' to be removed.
Note that if there is no '_' in the original name, then this may not work correctly. I didn't test that though.
Also note that the CALC_ATTR_FORMULA script command currently works on all loaded files. That may matter to your use case. It would probably be a nice to have a way to specify a particular layer to the CALC_ATTR_FORMULA command.
Anyways, a little complicated, but I hope it helps.
Best regards,
~Jeff
-
Thanks very much Jeff. That all makes sense. I will give it a try!
-
No problem -- let me know how it turns out.
~Jeff
-
Hi Jeff,
Just wanted to let you know that your approach has been working perfectly. Thanks again! Craig
-
Hi Craig -- glad to hear it's working for you! Thanks for using Global Mapper.
Cheers,
~Jeff
Categories
- 12.8K All Categories
- 5.7K Features Discussion
- 345 Downloading Imagery
- 1.3K Elevation Data
- 385 Georeferencing Imagery Discussion
- 636 GM Script Language
- 54 User Scripts
- 114 GPS Features
- 417 Projection Questions
- 825 Raster Data
- 1.3K Vector Data
- 6.6K Support
- 178 Announcement and News
- 912 Bug Report
- 558 SDK
- 1.2K Suggestion Box
- 3.7K Technical Support
- 569 Other Discussion
- 131 GIS Data Sources
- 27 Global Mapper Showcase
- 238 How I use Global Mapper
- 107 Global Mapper Forum Website