skip to Main Content

I’m trying to filter some journald logs which might have some-what similar information in different keys.

journalctl -o json | head -n 1000 | jq '.UNIT, .USER_UNIT, ._SYSTEMD_UNIT

Those 3 keys might have the unit name, depending on how the log entry was created (by the unit, by the system starting the unit, etc)… I don’t care about this and just want to get the related-unit.

How can I extract something like jq '.UNIT OR .USER_UNIT OR ._SYSTEMD_UNIT (or doesn’t work as it is a boolean converter to be used in select(), and | tries to route to a function)

I also cannot use + because when .UNIT key is present there will be something i don’t want to collect in ._SYSTEMD_UNIT.

2

Answers


  1. You can use the alternative operator //, which

    produces all the values of its left-hand side that are neither false nor null, or, if the left-hand side produces no values other than false or null, then // produces all the values of its right-hand side

    .UNIT // .USER_UNIT // ._SYSTEMD_UNIT
    

    You can also add a constant fourth option as the last default, which is returned if all previous three fail. This can be anything, including the empty string "" for blank lines, or even empty to disregard these inputs entirely.

    Login or Signup to reply.
  2. Another option is --output-field, but it has the side-effect that "_For the former, the "__CURSOR", "__REALTIME_TIMESTAMP", "__MONOTONIC_TIMESTAMP", and "BOOT_ID" fields are always printed."

    journalctl --output-fields=UNIT,USER_UNIT,SYSTEMD_UNIT  -o json | 
        jq 'del(.__CURSOR, ._BOOT_ID, .__MONOTONIC_TIMESTAMP, .__REALTIME_TIMESTAMP)' | 
        grep -v '{}'
    

    In the end the grep -v '{}' is needed to delete the empty results.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search