Hanfei Sun
Hanfei Sun

Reputation: 47071

How to finish this job in emacs?

The original string is like this:

  # chrom,name,strand,txStart

And the result should looks like this:

 # $1: chrom
 # $2: name
 # $3: strand
 # $4: txStart

Does anyone have idea of a quick way to do that?

Upvotes: 0

Views: 92

Answers (2)

phils
phils

Reputation: 73345

Lots of ways.

You could use a search and replace making use of the \# counter in the replacement. That's zero-based, so you'd either need to add a dummy replacement at the front to use up the zero, or else use the elisp replacement expression \,(1+ \#) instead.

You could use a keyboard macro, and insert a counter with C-xC-kTAB or <f3>. You can seed that counter by supplying a prefix argument when you start recording.

On Emacs 24 you can number the lines of a marked region using a custom format string with C-uC-xrN, so your format string could be # $%1d:

Upvotes: 6

syohex
syohex

Reputation: 2303

Evaluate following code and execute foo function on input line.

(require 'cl)

(defun foo ()
  (interactive)
  (let* ((str (buffer-substring-no-properties
               (line-beginning-position) (line-end-position)))
         (words-str (and (string-match "# \\(.+\\)$" str)
                         (match-string 1 str)))
         (buf (get-buffer-create "*tmp*")))
    (unless words-str
      (error "Line should be '# word1,word2,...'"))
    (with-current-buffer buf
      (erase-buffer)
      (loop with index = 1
            for word in (split-string words-str ",")
            do
            (progn
              (insert (format "# $%d: %s\n" index word))
              (incf index)))
      (pop-to-buffer buf))))

Upvotes: 1

Related Questions