Rosand Liu
Rosand Liu

Reputation: 409

extract variable items on single line using grep

I want to extract all date-time from files,

The content in my tmp.txt:

2020-10-17 16:04:08.590 [Thread-173] INFO  c.g.c.jobhandler.service.: "1600704240\\\\"2020-10-17 16:03:43\\\"-\
2020-10-17 16:05:03.780 [Thread-173] INFO  c.g.c.jobhandler.service.:"2020-10-17 16:05:43\\\"-\2020-10-17 16:05:57

This is my command:

grep -oP '\d*-\d*-\d* \d*:\d*:\d*' tmp.txt > res.txt

The result of my command

2020-10-17 16:04:08
2020-10-17 16:03:43
2020-10-17 16:05:03
2020-10-17 16:05:43
2020-10-17 16:05:57

I want the extracted date-time items also output in a single line as it's the position in the original file:

2020-10-17 16:04:08 2020-10-17 16:03:43
2020-10-17 16:05:03 2020-10-17 16:05:43 2020-10-17 16:05:57

How I can get this result. Thanks:)

Upvotes: 0

Views: 67

Answers (1)

Dave Cross
Dave Cross

Reputation: 69314

Pretty simple with Perl:

$ perl -nE 'say join " ", /(\d+-\d+-\d+ \d+:\d+:\d+)/g' tmp.txt 
2020-10-17 16:04:08 2020-10-17 16:03:43
2020-10-17 16:05:03 2020-10-17 16:05:43 2020-10-17 16:05:57
  • -n: run the code for every line in the input
  • -E: execute the code using all current Perl features (specifically, here I'm using say())
  • say: display a string followed by a newline
  • join " ": join together the following list using a space between each element
  • /.../: match this pattern
  • /.../g: match all occurrences of this pattern
  • /(...)/: capture (and return in a list) everything that matches the regex
  • \d+-\d+-\d+ \d+:\d+:\d+: regex to match a date

Upvotes: 3

Related Questions