bash bash循环跳过注释行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12488556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:18:51  来源:igfitidea点击:

bash loop skip commented lines

bashshell

提问by exvance

I'm looping over lines in a file. I just need to skip lines that start with "#". How do I do that?

我正在遍历文件中的行。我只需要跳过以“#”开头的行。我怎么做?

 #!/bin/sh 

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

Thanks for any help!

谢谢你的帮助!

回答by pilcrow

while read line; do
  case "$line" in \#*) continue ;; esac
  ...
done < /tmp/my/input

Frankly, however, it is often clearer to turn to grep:

然而,坦率地说,转向grep

grep -v '^#' < /tmp/myfile | { while read line; ...; done; }

回答by Slav

This is an old question but I stumbled upon this problem recently, so I wanted to share my solution as well.

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

If you are not against using some python trickery, here it is:

如果你不反对使用一些 python 技巧,这里是:

Let this be our file called "my_file.txt":

让它成为我们名为“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

Let this be our bash script called "my_script.sh":

让这成为我们的 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)

Calling the script will produce something similar to:

调用脚本将产生类似于:

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

Note:the blank line was not printed

注意:未打印空行

If you want blank lines you can change the script to:

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

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

Calling this script will produce something similar to:

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

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