2

How to remove the ### from grep output?

File containing:

### Invoked at: Wed Dec  7 22:24:35 2022 ###

My grep command:

grep -oP "Invoked at: \K(.*)" $file

Expected output:

Wed Dec  7 22:24:35 2022

Current output:

Wed Dec  7 22:24:35 2022 ###
tobyink
  • 13,478
  • 1
  • 23
  • 35
peace
  • 149
  • 7

3 Answers3

2

Use this:

grep -oP "Invoked at: \K.*\d+" "$file"

(no need parenthesis).

The regular expression matches as follows:

Node Explanation
Invoked at: 'Invoked at: '
\K resets the start of the match (what is Kept) as a shorter alternative to using a look-behind assertion: look arounds and Support of K in regex
.* any character except \n (0 or more times (matching the most amount possible))
\d+ digits (0-9) (1 or more times (matching the most amount possible))
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

You can remove a character from an output by adding | tr -d "#", so in your case this becomes:

grep -oP "Invoked at: \K(.*)" $file | tr -d "#"
Dominique
  • 16,450
  • 15
  • 56
  • 112
0

You could match the last digit before matching any character except #

grep -oP "\bInvoked at: \K[^#]*\d" $file

Output

Wed Dec  7 22:24:35 2022

The pattern matches:

  • \bInvoked at: \K Match Invoked at: and forget what is matched so far
  • [^#]* Repeat 0+ times any char except #
  • \d Match a digit

Regex demo

Or a more specific match for the whole example string using a case insensitive match with grep -oiP

^###\h+Invoked\h+at:\h+\K[a-z]+\h+[a-z]+\h+\d\d?\h+\d\d?:\d\d?:\d\d?\h+\d{4}(?=\h+###$)

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70