# Reference variable in grok match pattern

**URL:** <https://discuss.elastic.co/t/reference-variable-in-grok-match-pattern/210968>\
**Category:** Logstash\
**Created:** [December 7, 2019, 2:33pm UTC](https://discuss.elastic.co/t/reference-variable-in-grok-match-pattern/210968 "2019-12-07T14:33:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![marekful](https://avatars.discourse-cdn.com/v4/letter/m/c6cbf5/32.png) [@marekful](https://discuss.elastic.co/u/marekful)\
**Post date:** [December 7, 2019, 2:33pm UTC](https://discuss.elastic.co/t/reference-variable-in-grok-match-pattern/210968/1 "2019-12-07T14:33:34Z")

</div>

I define fields in filebeat.yml as below:

```
...
-
  paths:
    - /var/log/*-*/a-b-c.log*
  document_type: ...
  enabled: true
  fields:
    serviceNam: a-b-c
-
  paths:
    - /var/log/*-*/d-e-f.log*
  document_type: ...
  enabled: true
  fields
    serviceName: d-e-f

```

I want to use fields.serviceName in grok match pattern, e.g. when input is

```
... 123-bar-baz-a-b-c ...
... 456-foo-d-e-f ...

```

I want to match "123-bar-baz" and "456-foo" to a field. Both parts (e.g. 456-foo and d-e-f) can contain an arbitrary number of dashes, or any other characters but no spaces, and I always know (pass in via fielebeat.yml fields) the second half of the string (i.e. a-b-c and d-e-f in this example). The first part of the string (which I want to match) may or may not start with a number.

How can reference "fields.serviceName" in a grok match pattern? I tried a number of ways to no avail so far. E.g.

`...\[(?<serviceLongName>(?<buildName>(%{NUMBER:buildNumber}-)?(%{DATA})?)-%{[fields][serviceName]}),...`

Instead of `%{[fields][serviceName]}` I also tried `%{fields.serviceName}`, `%{serviceName}` I also tried to mutate { add\_field =\> {} } before grok match then reference the added field but nothing worked the way I need. Please advise.

---

<div class="post-metadata">

**Author:** ![Badger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/badger/32/25190_2.png) [@Badger](https://discuss.elastic.co/u/Badger)\
**Post date:** [December 7, 2019, 3:58pm UTC](https://discuss.elastic.co/t/reference-variable-in-grok-match-pattern/210968/2 "2019-12-07T15:58:23Z")

</div>

> [@marekful](#):
>
> I want to use fields.serviceName in grok match pattern

You cannot use a sprintf reference in a grok pattern. You would have to use a ruby filter and then do a match (or scan) against the value of the string.

---

<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:** [January 4, 2020, 3:58pm UTC](https://discuss.elastic.co/t/reference-variable-in-grok-match-pattern/210968/3 "2020-01-04T15:58:32Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
