Bash 匹配任何有任意数量空格的行,最多 #

Bash match on any lines that have any number of whitespace up to #

我需要在获取配置文件之前清理它。 我需要删除任何包含

的行

示例配置:

# comment
     # comment
dog=woof
cat=meow
moose=huuuuu #comment

# comment
### comment

我现在有这个

config_params="$(cat ./config_file.conf | grep -v "^#.* | awk -F '=' '{print}')"

问题是第 2 行, # comment 任意数量的 space,最多 #。我怎样才能匹配删除这样的行?

您可以使用这个 awk:

awk -F= 'NF == 2 {sub(/[[:blank:]]*#.*/, ""); print}' file

dog=woof
cat=meow
moose=huuuuu

或者,如果您只想打印键名,请使用:

awk -F= 'NF == 2 {sub(/[[:blank:]]*#.*/, ""); print }' file

dog
cat
moose

您可以使用

config_params=$(awk -F'=' '!/^[[:space:]]*#/{print }' ./config_file.conf)

参见online demo

#!/bin/bash
s='# comment
     # comment
dog=woof
cat=meow
moose=huuuuu #comment
 
# comment
### comment'
awk -F'=' '!/^[[:space:]]*#/{print }' <<< "$s"

输出:

dog
cat
moose

此处,^[[:space:]]*# 匹配字符串的开头,然后是零个或多个空格,然后是 #! 否定正则表达式匹配结果,因此仅“采用”不匹配此模式的行,然后仅打印它们的字段 1 值。

这是另一个使用 sed:

的有效解决方案
config=$(sed -r -e '/^$/d' -e '/^ *#/d' -e 's/^(.+)(#.*)$//' [[YOUR_CONFIG_FILE_NAME]])

我会使用 sed

$ cat file
# comment
     # comment
dog=woof
cat=meow
moose=huuuuu #comment

# comment
### comment

$ sed -E 's/ *#.*//; /^$/d;' file
dog=woof
cat=meow
moose=huuuuu

$ temp=$(mktemp)
$ sed -E 's/ *#.*//; /^$/d;' file>$temp
$ . $temp
$ echo $moose
huuuuu

此外,UUoC 是一种反模式,链接正则表达式工具也是。
为什么只将键保存到没有值的变量中?
(我添加了右括号和引号。)

如果那真的是你想要的,那么

config_params="$(cat ./config_file.conf | grep -v "^#.* | awk -F '=' '{print}')"

尝试

config_params="$(awk -F '=' '/^ *(#.*)*$/{next} {print }' ./config_file.conf)"

虽然我认为重点是 source 他们...