# Add a new field based on a regex capturing group

**URL:** <https://discuss.elastic.co/t/add-a-new-field-based-on-a-regex-capturing-group/28107>\
**Category:** Logstash\
**Created:** [August 26, 2015, 1:20pm UTC](https://discuss.elastic.co/t/add-a-new-field-based-on-a-regex-capturing-group/28107 "2015-08-26T13:20:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![DK\_3](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dk_3/32/48003_2.png) [@DK\_3](https://discuss.elastic.co/u/DK_3)\
**Post date:** [August 26, 2015, 1:20pm UTC](https://discuss.elastic.co/t/add-a-new-field-based-on-a-regex-capturing-group/28107/1 "2015-08-26T13:20:41Z")

</div>

The logstash events have `path` field with a value like: `/var/log/my-app_1-2015-08-26.0.log`

I want a filter that can take the `path` field and create a new field with just the `my-app_1` part of the `path` string

My attempt was with the `grok` & `mutate` filter but I'm not sure how to used the regex captured group 2:

```
grok {
       match => [
            "path", "%{GREEDYDATA:path}"
       ]
       add_field => ["log_path", "%{path}"]
   }

   mutate{
       gsub => {
            # replace everything except the 
            "log_path", "([\/\w]+\/)([\w\d_-]+)(-\d{4}-\d{2}-\d{2}\.\d\.log)", "<Use regex captured group 2 here>"
       }
   }
```

---

<div class="post-metadata">

**Author:** ![magnusbaeck](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/magnusbaeck/32/44943_2.png) [@magnusbaeck](https://discuss.elastic.co/u/magnusbaeck)\
**Post date:** [August 26, 2015, 1:50pm UTC](https://discuss.elastic.co/t/add-a-new-field-based-on-a-regex-capturing-group/28107/2 "2015-08-26T13:50:18Z")

</div>

Your grok filter doesn't serve any purpose. It's just a very convoluted way of copying a field. But you're right in that the grok filter is the right tool for the job. You don't need mutate. Just run grok against the `path` field and capture the string you're interested in:

```
grok {
  match => [
    "path",
    "^/var/log/%{GREEDYDATA:log_path}-%{YEAR}-%{MONTHNUM}-%{MONTHDAY}\.%{INT}\.log$"
  ]
}
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 6, 2017, 5:30am UTC](https://discuss.elastic.co/t/add-a-new-field-based-on-a-regex-capturing-group/28107/3 "2017-07-06T05:30:49Z")

</div>


