Search code examples
bashunixawkgrepcut

Split a text in several parts (Unix)


I have the next code:

mutate {
    add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ]
   }

if [type] == "batch" {
  if [idx] != "sipp" {
   mutate {
    add_field => [ "idx", "sipp"]
   }
  }
  if [message] == "" {
   drop { }
  }
}

mutate {
    add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ]
   }

I would like to obtain mutate's part.That is, in this case I would like get two parts only:

  • mutate { add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ] }

  • mutate { add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ] }

Not this part:

  • mutate { add_field => [ "idx", "sipp"] }

I have tried with grep,awk and cut. The problem is that these comands (grep,awk and cut) get the "mutate" which is inside "if [type]" too.

Example:

  • sed -n "/mutate\ {/,/}/p" file.txt

Output:

mutate {
        add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ]

mutate {
        add_field => [ "idx", "sipp"]
       }

mutate {
        add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ]

Thanks in advance,

Regards.


Solution

  • You can use sed to extract wanted mutate's part:

    sed -n '/^mutate {/,/   }/p' file.txt
    

    The result should be:

    mutate { add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ] } mutate { add_field => [ "NB_timestamp", "%{SYS_YEAR}/%{SYS_MONTH}/%{SYS_DAY} %{SYS_HOUR}:%{SYS_MIN}:%{SYS_SEC}" ] }