Ruby - First few characters (substring)

Hey All,

Trying to get the first 4 characters of a field that is obtained via XPATH.

This is what i currently have, but it copies everything rather then the first 4 characters. Been stumped on it for the past couple hours. Open to other methods other then ruby but haven't been able to find any other suggestions

ruby {
    code => "event.set('message_code', event.get('hostdata')[0,3])"
}

Is [hostdata] a string or an array? What does it look like in

output { stdout { codec => rubydebug } }

[hostdata] is a string field that is populated earlier via using the XML XPATH. I have also tried adding a mutate/convert prior to ensure that its a string.

Does the syntax look correct?

If it was populated using an xml filter and xpath it will be an array unless you have already done

mutate { replace => { "hostdata" => "[hostdata][0]" } }

Thanks Badger, looks like it was an array :stuck_out_tongue:. My bad.

Solution for anyone looking for one. This only needed to be populated on certain conditions (thus the if statement). Creates the field I want populated, converts hostdata to a string, then sets message_code to the first 4 characters.

  if ("HostRequest" in [action]) {
  	mutate{
  		add_field => {
  			"message_code" => "1"
  		}
  		replace => {
  			"hostdata" => "%{[hostdata][0]}"
  		}
  	}
  	ruby {
  		code => "event.set('message_code', event.get('hostdata')[0,4])"
  	}
  }

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