Home > other >  Replace substring from a field which is also a substring
Replace substring from a field which is also a substring

Time:08-07

I have this stdout from a command:

2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX

I only want to get the timestamp and the workflow name. In other words I want to return this:

2022-08-05T06:30:00.503053001Z workflow_name

but I can't figure out how to do it. I've tried various flavours of cut, but to no avail:

➜ echo 2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX | cut -d'/' -f 6
workflow_name
➜ echo 2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX | cut -d'/' -f 1,6
2022-08-05T06:30:00.503053001Z projects/workflow_name
➜ echo 2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX | cut -d'/' -f 0,6
cut: [-cf] list: values may not include zero

OK, as I've been writing this post I've figured out a way to do it using sed

➜ echo 2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX | cut -d'/' -f 1,6 | sed 's/projects\///g'
2022-08-05T06:30:00.503053001Z workflow_name

But that feels a bit clumsy. I was hoping there was a better way using cut. I would also quite like to remove the millisecond precision from the timestamp.

Open to suggestions as to how this could be improved

CodePudding user response:

awk is an option

$ echo "2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX" | awk -F '( |/)' '{print $1,$7}'
2022-08-05T06:30:00.503053001Z workflow_name

CodePudding user response:

If you can use perl :

perl -ne 'print "$1 $2\n" if (m{(.*?)\.\d Z.*?/workflows/([^/] )})' <<< "2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX"

CodePudding user response:

perhaps with sed

echo "2022-08-05T06:30:00.503053001Z projects/12345/locations/europe-west4/workflows/workflow_name/executions/a1f339e1-XXXX" | sed -E "s/([0-9T:\.\-]*Z).*workflows\/([a-zA-Z_]*)\/.*/\1 \2/g" 

on mac prompt my output

2022-08-05T06:30:00.503053001Z workflow_name
  • Related