emacs - 从代码块的结果创建组织表

标签 emacs org-mode org-babel

我正在尝试根据使用“;”的 CSV 文件的内容创建一个组织表作为分隔符。

我认为有一个源代码块来“cat”文件的内容然后将结果传递给创建表的函数会很容易,但我卡住了:我找不到方法使用第一个源代码块的“结果”。我知道的函数 (org-table-convert-region) 需要一个区域来工作,我不知道如何将“cat”-ed 文本作为一个区域传递。

#+NAME: csvraw
#+BEGIN_SRC sh :results raw
  cat afile.csv
#+END_SRC

感谢您帮助生成一个代码块,该代码块从我的 csv 文件中生成一个组织表,其中包含如下行:

ID;Region;SubRegion;Area;No
1234;Asia;India;45;2
24251;Europe;Romania;456;67

最佳答案

org-table-convert-region(绑定(bind)到 C-c |)可以相当简单地进行转换。唯一的技巧是指定 ; 作为分隔符。您可以通过使用适当的前缀参数调用它来做到这一点 - 文档字符串说:

(org-table-convert-region BEG0 END0 &optional SEPARATOR)

Convert region to a table.

The region goes from BEG0 to END0, but these borders will be moved
slightly, to make sure a beginning of line in the first line is included.

SEPARATOR specifies the field separator in the lines.  It can have the
following values:

(4)     Use the comma as a field separator
(16)    Use a TAB as field separator
(64)    Prompt for a regular expression as field separator
integer  When a number, use that many spaces, or a TAB, as field separator
regexp   When a regular expression, use it to match the separator
nil      When nil, the command tries to be smart and figure out the
         separator in the following way:
         - when each line contains a TAB, assume TAB-separated material
         - when each line contains a comma, assume CSV material
         - else, assume one or more SPACE characters as separator.

(64)的值就是连续三个C-u,所以过程如下:

  • 使用 C-x i 插入 CSV 文件。
  • C-x C-x 将插入的内容标记为事件区域。
  • C-u C-u C-u C-c | ; RET

更酷的是,在 CSV 文件的第一行和其余行之间留一个空行,将自动使第一行成为表格中的标题。

您也可以将其封装在代码块中:

#+begin_src elisp :var file="/tmp/foo.csv" :results raw
  (defun csv-to-table (file)
    (with-temp-buffer
      (erase-buffer)
      (insert-file file)
      (org-table-convert-region (point-min) (point-max) ";")
      (buffer-string)))

  (csv-to-table file)
#+end_src

#+RESULTS:
| a | b | c |
|---+---+---|
| d | e | f |
| g | h | i |

关于emacs - 从代码块的结果创建组织表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55598919/

相关文章:

shell - 在 Emacs 中使用 z(跳转)来查找目录

emacs - 如何在 emacs 艺术家模式下在矩形内写入文本?

emacs - 为 Org-mode 中的每个条目分配 ID

emacs - 使用 org-babel 进行文学编程

org-mode - 导出时显示组织模式下代码块的名称?

emacs - 用 emacs 替换 ssh+screen+editor

emacs - 组织模式任务依赖性不起作用

Emacs,如何在组织模式下仅显示当前任务并隐藏其他任务?

Emacs 组织模式 : define variable in buffer and access variable

emacs - emacs lisp 中词法绑定(bind)和 defvar 之间的奇怪交互