Saturday, September 4, 2021

Re: How to replace pattern with shell command's output using matched pattern

On 2021-09-04 09:15, Lifepillar wrote:
> Use case at hand: replace Unix timestamps with date/time in a log
> file:
>
> [1630720618] unbound[63495:0] info: 127.0.0.1 foo.bar.com AAAA IN
> [1630720618] unbound[63495:1] info: 127.0.0.1 foo.bar.com A IN
> ...
>
> The shell command I'd apply is `date -r <timestamp>`. How would you
> perform the substitution?
>
> The desired output is:
>
> [Sat Sep 4 03:56:58 CEST 2021] unbound[63495:0] info: 127.0.0.1
> foo.bar.com AAAA IN [Sat Sep 4 03:56:58 CEST 2021]
> unbound[63495:1] info: 127.0.0.1 foo.bar.com A IN ...

This should do the trick

%s/\[\zs\d\+\ze\]/\=substitute(system('date -r '.submatch(0)), '\n',
'', '')

It took a bit of testing to get right since GNU `date` expects a file
for -r where FreeBSD `date` uses it like you wanted, so I had to test
on the right OS. :-)

It's not particularly speedy, so if you have thousands of them, you're
invoking a command for every single one of them, but it's vastly
faster than doing each by hand.

It should also allow you to alter the format if you prefer (some
shell commands mung "%" with the current filename, but in this case,
system() doesn't, so you're safe)

-tim



--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/20210904080843.46ddb91d%40bigbox.attlocal.net.

No comments:

Post a Comment