如何在bash for循环中跳过带注释(#space)的行

时间:2015-07-13 14:33:24

标签: linux bash unix

使用以下代码:

#!/bin/bash
export LC_ALL=C

for input_file in $(<inputflist.txt)
do
    case "$input_file" in \#*) continue ;; esac
    echo $input_file

done

inputflist.txt包含以下内容:

# foo.txt
bar.txt

我希望它只打印最后一行bar.txt,但它会打印出来:

foo.txt
bar.txt

这样做的正确方法是什么?

3 个答案:

答案 0 :(得分:3)

这应该有效:

while IFS= read -r line; do
   [[ $line =~ ^[[:blank:]]*# ]] && continue
   echo "$line"
done < inputflist.txt

<强>输出:

bar.txt

答案 1 :(得分:3)

Don't read lines with for,改为使用while循环:

while IFS= read -r line;do
[[ $line =~ ^[[:space:]]*# ]] || echo "$line"
done <file

注意:

  1. 如果未正确设置IFS,则会丢失任何缩进。
  2. You should almost always use the -r option with read

答案 2 :(得分:2)

中的错误
for input_file in $(grep -v "^#" inputflist.txt); do
  echo $input_file
done

或只是

grep -v "^#" inputflist.txt