Bash 循环获取文件中的行,跳过注释和空行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24537483/
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 10:46:52  来源:igfitidea点击:

Bash loop to get lines in a file, skipping comments and blank lines

bash

提问by Cat5InTheCradle

I want to get lines from a file that might look like this

我想从一个看起来像这样的文件中获取行

# This will be skipped
But this line will not
Nor this one

# this and the above blank line will be skipped
but not this one!

The code I have for handling the comments is this:

我处理评论的代码是这样的:

#!/bin/bash

hosts = inventory/hosts

# List hosts we're going to try to connect to
cat $hosts | while read line; do
  case "$line" in \#*) continue ;; esac
        echo $line
done

But that doesn't skip the whitespace. Not sure what I need to add. Is there a better way to do this?

但这并没有跳过空格。不确定我需要添加什么。有一个更好的方法吗?

回答by anubhava

You can tweak loop like this:

您可以像这样调整循环:

while read -r line; do
    [[ -n "$line" && "$line" != [[:blank:]#]* ]] && echo "$line"
done < file

回答by Jordan Running

This ought to do. No loop needed unless you need to do further operations on the remaining lines.

这是应该的。除非您需要对剩余的行做进一步的操作,否则不需要循环。

#!/bin/bash

hosts="inventory/hosts"

# List hosts we're going to try to connect to
grep -vE '^(\s*$|#)' $hosts

回答by Tripp Kinetics

How about:

怎么样:

#!/bin/bash

hosts = inventory/hosts

# List hosts we're going to try to connect to
sed -e '/^\s*$/ d' -e '/^#/ d' $hosts | while read line; do
    echo $line
done

回答by jimm-cl

If you just want to skip comments and blank lines, then maybe a simple sedcommand would be enough:

如果您只想跳过注释和空行,那么也许一个简单的sed命令就足够了:

$ cat test
# This will be skipped
But this line will not
Nor this one

# this and the above blank line will be skipped
but not this one!

Try something like sed '/^#/d'to get rid of the comments, and sed '/^$/d'to get rid of blank lines.

尝试诸如sed '/^#/d'删除注释和sed '/^$/d'删除空白行之类的方法。

$ sed '/^#/d' test | sed '/^$/d'
But this line will not
Nor this one
but not this one!