在Emacs Lisp中awk'{print $ 2,",",$ 1}'?

5 awk elisp

偶尔我使用AWK来提取和/或反转数据文件中的列.

awk '{print $2,",",$1}' filename.txt
Run Code Online (Sandbox Code Playgroud)

我如何使用Emacs Lisp做同样的事情?

(defun awk (filename col1 &optional col2 col3 col4 col5)
  "Given a filename and at least once column, print out the column(s)
values in the order in which the columns are specified."
...
)
;; Test awk
(awk "filename.txt" 1); Only column 1
(awk "filename.txt" 2 1); Column 2 followed by column 1
(awk "filename.txt" 3 2 1); Columns 3,2 then 1
Run Code Online (Sandbox Code Playgroud)

样品filename.txt:

a   b  c
1   2  5
Run Code Online (Sandbox Code Playgroud)

样本输出:

b , a
2 , 1
Run Code Online (Sandbox Code Playgroud)

Tre*_*son 2

您打算如何使用这个?您打算将其用作命令行脚本吗?在这种情况下,您需要像这个hello world Question一样打包它。

或者,您是否计划以交互方式使用它,在这种情况下您可能希望将输出放在新的缓冲区中......

这段代码完成了基础知识。您需要更新它以匹配您的使用模型。

(defun awk (filename &rest cols)
  "Given a filename and at least once column, print out the column(s) values
in the order in which the columns are specified."
  (let* ((buf (find-file-noselect filename)))
    (with-current-buffer buf
      (while (< (point) (point-max))
        (let ((things (split-string (buffer-substring (line-beginning-position) (line-end-position))))
              (c cols)
              comma)
          (while c
            (if comma
                (print ", "))
            (print (nth (1- (car c)) things))
            (setq comma t)
            (setq c (cdr c)))
          (print "\n")
          (forward-line))))
    (kill-buffer buf)))
Run Code Online (Sandbox Code Playgroud)