0

I am working on Linux and I'm running the following:

$ ls -t postgresq*.log | head -n1 | xargs grep "ALTER USER"  
< pg_user 2021-07-15 05:03:41.609 EDT > LOG:  statement: ALTER USER username WITH ENCRYPTED PASSWORD 'JUly@#12' valid until '2021-07-20';

But I only want to grep the string below:

ALTER USER username WITH ENCRYPTED PASSWORD 'JUly@#12' valid until '2021-07-20';
terdon
  • 242,166

2 Answers2

0

Just use -o (from man grep):

$ man grep | grep -P -A1 -- '^\s+-o'
       -o, --only-matching
              Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Since -o will make grep print only the matched part of the line, you can just search for ALTER USER.* to match everything from ALTER USER to the end:

$ ls -t postgresq*.log | head -n1 | xargs grep -oP 'ALTER USER.*'
ALTER USER username WITH ENCRYPTED PASSWORD 'JUly@#12' valid until '2021-07-20';

Note that parsing the output of ls is generally not a good idea, but it is probably safe in your case since these log files should have simple names.

terdon
  • 242,166
0

Using teh zsh shell and sed to find and modify the line you're looking for:

sed '/ALTER USER/ s/.*statement: //' postgresq*.log(.om[1])

The globbing pattern postgresq*.log(.om[1]) was explained in some detail in my answer to your previous question. In short, it expands to the name of the most recently modified regular file whose name matches postgresq*.log, or it generates an error if no names matches the pattern.

The sed expression

/ALTER USER/ s/.*statement: //

will find any line that contains the string ALTER USER in the given file, and then delete everything from the start of that line up to the space after the string statement:.

Kusalananda
  • 333,661