Can I add leading zeros to a field?

Question about Logstash (Elastic Stack). Can someone give me a pointer on how to add a new field (add_field) that will format a number with leading zeroes?
e.g. given somefield == 123 then someotherfield == "00123".

Do you always want to leading zeroes or do you always want the string to be five characters long? (Either way the answer would be to use a mutate filter's gsub option, but an exact answer depends on the details.)

Yes.and yes. Always leading zeroes always five chars long.

Unless the field already is a string use a mutate filter's convert option to coerce it into a string. Then do this:

if [somefield] =~ /^\d{3}$/ {
  mutate {
    replace => {
      "somefield" => "00%{somefield}"
    }
  }
}

This one takes care of strings of length three that need to zeroes prepended. Repeat to support strings of different lengths.

You could also use a ruby filter. Such a configuration would be more compact and possibly faster.

1 Like

Thank you Magnus

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