bash循环跳过注释行

时间:2012-09-19 04:23:11

标签: bash shell

我循环遍历文件中的行。我只需要跳过以"#"开头的行。 我该怎么做?

 #!/bin/sh 

 while read line; do
    if ["$line doesn't start with #"];then
     echo "line";
    fi
 done < /tmp/myfile

感谢您的帮助!

2 个答案:

答案 0 :(得分:16)

while read line; do
  case "$line" in \#*) continue ;; esac
  ...
done < /tmp/my/input
然而,坦率地说,转向grep

通常更为明确
grep -v '^#' < /tmp/myfile | { while read line; ...; done; }

答案 1 :(得分:0)

这是一个古老的问题,但是最近我偶然发现了这个问题,所以我也想分享我的解决方案。

如果您不反对使用某些python技巧,那就是:

让我们将其命名为“ my_file.txt”:

this line will print
this will also print # but this will not
# this wont print either
      # this may or may not be printed, depending on the script used, see below

这就是我们的bash脚本“ my_script.sh”:

#!/bin/sh

line_sanitizer="""import sys
with open(sys.argv[1], 'r') as f:
    for l in f.read().splitlines():
        line = l.split('#')[0].strip()
        if line:
            print(line)
"""
echo $(python -c "$line_sanitizer" ./my_file.txt)

调用脚本将产生类似于:

$ ./my_script.sh
this line will print
this will also print

注意:未打印空白行

如果要空白行,可以将脚本更改为:

#!/bin/sh

line_sanitizer="""import sys
with open(sys.argv[1], 'r') as f:
    for l in f.read().splitlines():
        line = l.split('#')[0]
        if line:
            print(line)
"""
echo $(python -c "$line_sanitizer" ./my_file.txt)

调用此脚本将产生类似于:

$ ./my_script.sh
this line will print
this will also print


相关问题