【问题标题】:How do I delete the newline from a process output?如何从流程输出中删除换行符?
【发布时间】:2012-12-28 19:47:47
【问题描述】:

我调用 git 获取顶层目录(根据 Is there a way to get the git root directory in one 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))))

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

【问题讨论】:

    标签: elisp


    【解决方案1】:

    我觉得你可以的

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

    【讨论】:

    • 这不只是删除输出末尾的换行符。我添加了一个替代答案。
    • 你能解释一下为什么不吗?
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

      (substring output-string 0 -1)
      

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

      (substring
        (shell-command-to-string "git rev-parse --show-toplevel")
        0 -1)
      

      【讨论】:

        【解决方案4】:

        如果你对 awesome 外部包没问题。

        使用s-trim

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-21
          • 2011-05-18
          • 2020-06-04
          相关资源
          最近更新 更多