bash循环跳过注释行

exv*_*nce 13 bash shell

我正在循环文件中的行.我只需要跳过以"#"开头的行.我怎么做?

 #!/bin/sh 

 while read line; do
    if ["$line doesn't start with #"];then
     echo "line";
    fi
 done < /tmp/myfile
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

pil*_*row 17

while read line; do
  case "$line" in \#*) continue ;; esac
  ...
done < /tmp/my/input
Run Code Online (Sandbox Code Playgroud)

然而,坦率地说,通常更清楚地转向grep:

grep -v '^#' < /tmp/myfile | { while read line; ...; done; }
Run Code Online (Sandbox Code Playgroud)

  • 另一种选择是`[[$ line = \#*]] && continue`. (7认同)
  • 另一个选择(如果由于某种原因而想避免使用“ grep”)可能是“ if [[$ line =〜^#]];”。然后继续;fi`。 (3认同)
  • 要删除空格(仅)在`#`之前的行,请使用`grep -v'^\s*#'</ tmp/myfile` - 这符合`case`解决方案,假设`read`剥离前导和尾随空格. (2认同)
  • 如果 while 循环需要修改当前 shell 中的变量,grep 解决方案将不起作用,因为循环在子 shell 中运行(除非 bash 4.2 可用并且使用了 `set -o lastpipe`)。默认情况下,其他 shell 可能会在当前 shell 中运行 while 循环。 (2认同)