【问题标题】:how to use vim to open every .txt file under a directory (with Bash)如何使用 vim 打开目录下的每个 .txt 文件(使用 Bash)
【发布时间】:2012-11-13 09:32:41
【问题描述】:

我正在尝试以下使用vim 打开当前目录下的每个txt 文件。

find . -name "*.txt" -print | while read aline; do
  read -p "start spellchecking fine: $aline" sth
  vim $aline
done

bash 中运行它会抱怨

Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...
Vim: Finished.

谁能解释可能出现的问题?另外,我打算在使用vim之前使用read -p进行提示,没有成功。

【问题讨论】:

    标签: bash vim while-loop


    【解决方案1】:

    试试:

    vim $( find . -name "*.txt" )
    

    要修复您的解决方案,您可以(可能)这样做:

    find . -name "*.txt" -print | while read aline; do
          read -p "start spellchecking fine: $aline" sth < /dev/tty
          vim $aline < /dev/tty
    done
    

    问题是整个 while 循环都从 find 中获取输入,而 vim 继承了该管道作为其标准输入。这是从终端获取 vim 输入的一种技术。 (但并非所有系统都支持/dev/tty。)

    【讨论】:

    • 是否可以在打开vim之前提示“read -p”?
    【解决方案2】:

    使用shopt -s globstar,您可以清除 find,从而使 bash 不在接收 find 输出的子 shell 中执行 vim:

    shopt -s globstar
    shopt -s failglob
    for file in **/*.txt ; do
        read -p "Start spellchecking fine: $file" sth
        vim "$file"
    done
    

    。另一个想法是使用

    for file in $(find . -name "*.txt") ; do
    

    (如果没有包含空格或换行符的文件名。)

    【讨论】:

    • endfor 很有趣但不正确...用done 替换它。另外,你应该引用"$file"
    • @gniourf_gniourf 谢谢。在zsh工作时你不需要关心,所以我忘了引用。
    • 也许你也应该shopt -s nullglob,以防万一没有文件匹配**/*.txt
    • @gniourf_gniourf 它适用于这种情况,但 zsh 行为恕我直言更好:glob 扩展为空会导致错误并停止执行:failglob 选项。 nullglob 仅在有限的安全案例中需要。
    • 对于nullglob,它什么也不做(就像find使用的OP一样)。 failglob 可能更好,你说得对。
    【解决方案3】:

    通常最简单的解决方案是最好的,我相信就是这样:

    vim -o `find . -name \*.txt -type f`
    

    -type f 是为了确保只打开以 .txt 结尾的文件,因为您不排除可能存在名称以“.txt”结尾的子目录的可能性。

    这将在 vim 的单独窗口/缓冲区中打开每个文件,如果您不需要这样做并且乐于使用 :next 和 :prefix 浏览文件,请从建议的命令中删除“-o”-上面一行。

    【讨论】:

      【解决方案4】:

      在一个 vim 实例中打开所有文件的正确方法是(前提是文件数不超过最大参数数):

      find . -name '*.txt' -type f -exec vim {} +
      

      另一种完全回答 OP 的可能性,但好处是对于包含空格或有趣符号的文件名是安全的。

      find . -name '*.txt' -type f -exec bash -c 'read -p "start spellchecking $0"; vim "$0"' {} \;
      

      【讨论】:

      • 愤怒的投票者,请留言解释为什么您认为这没有用或错误。这样做可能会更好,这样我就可以修复答案或删除它!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      相关资源
      最近更新 更多