[英]How to replace specific section of text in a file, with text from url in bash?
[英]grep get text from specific section only from bash
我有以下配置文件:
[general]
a=b
b=c
...
mykey=myvalue
n=X
[prod]
a=b
b=c
mykey=myvalue2
...
我只想從[general]
部分獲取mykey
。
我所嘗試的是以下內容:
cat my.config | grep mykey
除了我得到兩個結果:
mykey=myvalue
mykey=myvalue2
[general]
部分並不總是出現在配置文件的第一部分。
如何使用 linux 命令獲取出現在[general]
部分下的mykey
?
這是一個帶有 awk 的:
$ awk -v RS="" ' # process empty line separated blocks
$1=="[general]" { # if a block starts with a key string
for(i=2;i<=NF;i++) # iterate records or fields in this case
if($i~/^mykey=/) { # find the key
print $i # and output the field
exit # once found, no point in continuing the search
}
}' file
輸出:
mykey=myvalue
您可以獲得 [general] 和下一個平方參數之間的值。
awk '/^\[/{f=0} f; /\[general\]/{f=1}' file.config | grep mykey
你可以使用python腳本
ini2arr.py
#!/usr/bin/env python
import sys, ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(sys.stdin)
for sec in config.sections():
print "declare -A %s" % (sec)
for key, val in config.items(sec):
print '%s[%s]="%s"' % (sec, key, val)
然后
eval "$(cat t.ini | ./ini2arr.py)"
echo ${general["mykey"]}
編輯或:
#!/usr/bin/env python
import sys
import ConfigParser
section_filter = sys.argv[1]
key_filter = sys.argv[2]
config = ConfigParser.ConfigParser()
config.readfp(sys.stdin)
print '%s[%s]="%s"' % (section_filter, key_filter, config.get(section_filter, key_filter))
然后
cat t.ini | ./ini2arr.py prod a
這是另一個awk
解決方案(使用標准的 linux awk/gawk)
/\[general\]/,/^$/ {if ($0 ~ "mykey") print}
/\[general\]/,/^$/ # match lines range : starting with "[general]" and ending with "" (empty line)
{ # for each line in range
if ($0 ~ "mykey") # if line match regex pattern "mykey"
print $0 # print the line
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.