加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

在Emacs Lisp中awk'{print $2,“,”,$1}’?

发布时间:2020-12-14 02:11:56 所属栏目:Linux 来源:网络整理
导读:偶尔我使用AWK来提取和/或反转数据文件中的列. awk '{print $2,",$1}' filename.txt 我如何使用Emacs Lisp做同样的事情? (defun awk (filename col1 optional col2 col3 col4 col5) "Given a filename and at least once column,print out the column(s)val
偶尔我使用AWK来提取和/或反转数据文件中的列.

awk '{print $2,",$1}' filename.txt

我如何使用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

示例filename.txt:

a   b  c
1   2  5

样本输出:

b,a
2,1

解决方法

你打算如何使用它?您是否计划将其用作命令行脚本?在这种情况下,您需要像 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)))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读