[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Search and replace for a single file using a pattern file

From: tomas
Subject: Re: Search and replace for a single file using a pattern file
Date: Thu, 4 Jan 2018 11:50:20 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

Hash: SHA1

On Thu, Jan 04, 2018 at 02:02:29AM -0800, Angus Comber wrote:
> I have some horrible logs where integers are printed for states and I want to 
> do a global search and replace on the file to eg replace integer x with a 
> string.
> I can obviously do individually using c-m-% but that is fairly laborious.  So 
> use of a search and replace mapping in a text file would be really convenient.
> Is this possible?  any suggestions?

Yes, enter the \,(...) replacement magic. This construct
means "evaluate the expression after the \, as an elisp
expression". Here's some shortened version of your problem.
Assume I want to replace the digits 1, 2, 3 at the beginning
of the line by words assigned to them. An association list
seems to be a simple representation for that mapping:

  #+BEGIN_SRC emacs-lisp
  (defvar my-codes
    '((1 . bread)
      (2 . cheese)
      (3 . wine)))

Add associations to taste ;-P

Now check that our alist is working as supposed: to get the
"value" part for a "key", there's alist-get:

  #+BEGIN_SRC emacs-lisp
  (alist-get 2 my-codes)

And that results in...

  : cheese

Seems fine. Our test data (NOTE in real life not indented. I
indent it here to ease reading):

  1 was my first meal
  2 came after that and
  3 to rinse it all

Apply the following "query-replace regexp":

  ^\([0-9]\) → \,(alist-get (string-to-number \1) my-codes)

Note two things:

 - within the lisp expression you have access to the partial
   matches as \1, \2 etc. They are substituted as strings
   (that's why there is the (string-to-number ...) there:
   our assoc list above has numbers as keys)

 - a more convenient way of writing (string-to-number \1)
   in the replacement string exists: it's just \#1 (likewise
   for 2, 3, etc, of course).

- -- tomás

Version: GnuPG v1.4.12 (GNU/Linux)


reply via email to

[Prev in Thread] Current Thread [Next in Thread]