使vim在循环时正确缩进管道

问题描述

我一直在使用以下代码行来读取1.1.1.1中的ip 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

done语法在vim代码编辑器中仍然不能正确缩进(现在是否可以执行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

解决方法

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