【问题标题】:How to skip line with comment (# space ) in bash for loop [duplicate]如何在bash for循环中跳过带有注释(#空格)的行[重复]
【发布时间】:2015-10-01 21:15:09
【问题描述】:

使用以下代码:

#!/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

正确的做法是什么?

【问题讨论】:

    标签: linux bash unix


    【解决方案1】:

    这应该可行:

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

    输出:

    bar.txt
    

    【讨论】:

    • [[:blank:]]* 在这里没用,$line 没有前导空格,它在这里丢失了任何缩进(因为 IFS 设置不正确)。所以删除这部分正则表达式将产生相同的结果。
    • 没错,感谢您的评论。它需要在read 之前使用IFS= 来保留空格。
    【解决方案2】:

    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

    【讨论】:

    • [[:space:]] 也匹配换行符
    • @anubhava 在这里没有任何区别,是吗?
    • 这只是一个仅供参考的评论。是的,它不会影响此脚本,因为 $line 没有任何换行符。
    • 我更喜欢 OP 的 case 语句而不是 [[ 正则表达式。
    • 真;正则表达式工具允许更通用的表达式。
    【解决方案3】:

    有什么问题

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

    或者干脆

    grep -v "^#" inputflist.txt
    

    ?

    【讨论】:

    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    相关资源
    最近更新 更多