[英]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$1}')"
問題是第 2 行, # comment
最多#
的任意數量的空格。 我怎樣才能匹配刪除這樣的行?
您可以使用此awk
:
awk -F= 'NF == 2 {sub(/[[:blank:]]*#.*/, ""); print}' file
dog=woof
cat=meow
moose=huuuuu
或者,如果您只想打印鍵名,請使用:
awk -F= 'NF == 2 {sub(/[[:blank:]]*#.*/, ""); print $1}' file
dog
cat
moose
您可以使用
config_params=$(awk -F'=' '!/^[[:space:]]*#/{print $1}' ./config_file.conf)
請參閱在線演示:
#!/bin/bash
s='# comment
# comment
dog=woof
cat=meow
moose=huuuuu #comment
# comment
### comment'
awk -F'=' '!/^[[:space:]]*#/{print $1}' <<< "$s"
Output:
dog
cat
moose
在這里, ^[[:space:]]*#
匹配字符串的開頭,然后是零個或多個空格,然后是#
。 的!
否定正則表達式匹配結果,因此僅“采用”不匹配此模式的行,然后僅打印它們的 Field 1 值。
這是使用sed
的另一個有效解決方案:
config=$(sed -r -e '/^$/d' -e '/^ *#/d' -e 's/^(.+)(#.*)$/\1/' [[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$1}')"
嘗試
config_params="$(awk -F '=' '/^ *(#.*)*$/{next} {print $1}' ./config_file.conf)"
雖然我認為重點是source
它們......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.