我想从一个看起来像这样的文件中获取行
# 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!
我处理评论的代码是:
#!/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
但这并没有跳过这个空白。不确定我需要添加什么。有更好的方法吗?
答案 0 :(得分:3)
你可以像这样调整循环:
while read -r line; do
[[ -n "$line" && "$line" != [[:blank:]#]* ]] && echo "$line"
done < file
答案 1 :(得分:3)
这应该做的。除非您需要对其余行进行进一步操作,否则不需要循环。
#!/bin/bash
hosts="inventory/hosts"
# List hosts we're going to try to connect to
grep -vE '^(\s*$|#)' $hosts
答案 2 :(得分:1)
怎么样:
#!/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
答案 3 :(得分:1)
如果你只是想跳过评论和空行,那么简单的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!
尝试使用类似sed '/^#/d'
的内容来删除注释,并sed '/^$/d'
删除空白行。
$ sed '/^#/d' test | sed '/^$/d'
But this line will not
Nor this one
but not this one!