首页 > 解决方案 > 使vim正确缩进管道while循环

问题描述

我一直在使用这行代码来读取 ip 1.1.1.1in ip_list.txt,存储在变量中line然后打印出来:

if [ true == false ]; then # Example
ip="1.1.1.1"
grep -r $ip ip_list.txt | while read -r line ; do
echo "Line is: $line"
done
fi

代码运行良好,但 vim 没有正确缩进此代码。当我这样做时g=GG,您可以看到done语法应该在语法下方排列,grep但它在语句的左侧if。它会在 vim 中像这样缩进:

if [ true == false ]; then
    ip="1.1.1.1"
    grep -r $ip ip_list.txt | while read -r line ; do
    echo "Line is: $line"
done # Went to the left. Not lined up with grep
fi

即使我删除了;, 并让do底部像这样:

if [ true == false ]; then # Example
ip="1.1.1.1"
grep -r $ip ip_list.txt | while read -r line
do
echo "Line is: $line"
done
fi

vim 代码编辑器中的done语法仍然没有正确缩进(如果我这样做的话g=GG):

if [ true == false ]; then
        ip="1.1.1.1"
        grep -r $ip ip_list.txt | while read -r line
do
        echo "Line is: $line"
done # not lined up with grep syntax
fi

有什么方法可以编辑此代码以便 vim 可以正确缩进?

预期的输出应该是:

if [ true == false ]; then
    ip="1.1.1.1"
    grep -r $ip ip_list.txt | while read -r line ; do
        echo "Line is: $line"
    done
fi

或者应该是

if [ true == false ]; then
    ip="1.1.1.1"
    grep -r $ip ip_list.txt | while read -r line
    do
        echo "Line is: $line"
    done
fi

标签: vimindentation

解决方案


vim 的缩进正则表达式对此不够聪明。如果您愿意,您可以自己编辑语法文件:用于:scriptnames查看 vim 加载的文件以查看文件的完整路径syntax/sh.vim

一个更简单的方法是改变你的 bash 语法:

if [ true == false ]; then # Example
ip="1.1.1.1"
while read -r line; do
echo "Line is: $line"
done < <(grep -r $ip ip_list.txt )
fi

正确缩进

if [ true == false ]; then # Example
  ip="1.1.1.1"
  while read -r line; do
    echo "Line is: $line"
  done < <(grep -r $ip ip_list.txt )
fi

推荐阅读