Awk '{print $ 2, ",", $ 1}' in Emacs Lisp?

Sometimes I use AWK to retrieve and / or modify columns in a data file.

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

How do I do the same with 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

An example filename.txt:

a   b  c
1   2  5

Output Example:

b , a
2 , 1
+5
source share
3 answers

How are you going to use this? Do you plan to use it as a command line script? In this case, you need to pack it as follows hello world question .

Or do you plan to use it interactively, in which case you probably want to get the result in a new buffer ...

This code gets the basics. You will need to update it to fit your usage model.

(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)))
+2

script, Unix. , , -args-left .


#!/usr/bin/emacs --script

;; ./awk.el; # Change the last line of this file to contain the desired values.
;;
(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 (&lt (point) (point-max))
        (let ((things (split-string (buffer-substring (line-beginning-position) 
                          (line-end-position))))
              (c cols)
              comma)
          (while c
            (if comma
                (princ ", "))
            (princ (nth (1- (car c)) things))
            (setq comma t)
            (setq c (cdr c)))
            (princ "\n")
          (forward-line))))
    (kill-buffer buf)))

(awk "/tmp/foo.txt" 2 1)

0

dash.el s.el:

(defun print-columns (s &rest is)
  (s-join "\n"
          (--map (s-join ", "
                         (-select-by-indices is (cons it (s-split " " it t))))
                 (s-lines s))))

(print-columns "a  b c\n1  2 3" 3 2 1 0) ; output:
;; c, b, a, a  b c
;; 3, 2, 1, 1  2 3

awk ( ), ( ). , c - a b c. print-columns , s-lines, , s-join, . dash -select-by-indices, , :

(-select-by-indices '(2 1 0) '(a b c d e)) ; => (c b a)
0

All Articles