14

我调用 git get the toplevel dir (根据 Is there a way to get the git root directory in a command? )。

(let ((tmpbuffer (get-buffer-create (make-temp-name "git"))))
  (call-process "git" nil tmpbuffer nil "rev-parse" "--show-toplevel")
  (with-current-buffer tmpbuffer
    (with-output-to-string
      (princ (buffer-string))
      (kill-buffer))))

但是返回的字符串中有一个尾随换行符。我不知道如何摆脱它。

4

4 回答 4

16

我认为你可以做到

(replace-regexp-in-string "\n$" "" 
              (shell-command-to-string "git rev-parse --show-toplevel"))
于 2012-12-28T20:33:20.320 回答
9

如果您只想在输出的最后删除换行符,请使用

(replace-regexp-in-string "\n\\'" "" 
  (shell-command-to-string "git rev-parse --show-toplevel"))

接受的答案还用"\n\n"单个换行符 () 替换输出中的换行符对 ( "\n"),因为$匹配字符串末尾或换行符之后,而\\'仅匹配字符串末尾。

于 2015-04-21T15:54:40.497 回答
5

假设它存储在一个变量output-string中,最后的换行符可以这样删除:

(substring output-string 0 -1)

使用这种shell-command方式,它看起来像这样:

(substring
  (shell-command-to-string "git rev-parse --show-toplevel")
  0 -1)
于 2019-02-03T14:07:38.107 回答
2

如果你对很棒的外部包没问题。

使用s-trim

ELISP> (shell-command-to-string "light -G")
"60.00\n"

ELISP> (s-trim (shell-command-to-string "light -G"))
"60.00"
于 2020-04-10T05:44:14.587 回答