如何使用vim打开目录下的每个.txt文件(使用Bash)

时间:2012-11-25 21:46:58

标签: bash vim while-loop

我正在尝试以下操作使用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进行提示,但没有成功。

4 个答案:

答案 0 :(得分:11)

尝试:

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继承该管道作为其stdin。这是一种让vim输入来自终端的技术。 (但并非所有系统都支持/dev/tty。)

答案 1 :(得分:1)

使用shopt -s globstar,您可以清除查找,从而使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

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

答案 2 :(得分:0)

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

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

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

这将在vim中的单独窗口/缓冲区中打开每个文件,如果您不需要这个,并且很高兴使用:next和:前缀来浏览文件,从建议的命令中删除“-o” - 在上面。

答案 3 :(得分:0)

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

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

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

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