获取包含特定字词

时间:2018-04-10 04:16:08

标签: string awk sed get next

使用openwrt我通常使用UCI来获取某些脚本的变量数据。这样的事情:

uci get /etc/config/network.lan.data

不幸的是我一般都没有找到类似Linux的东西,但我相信awk或sed可以做到这一点,而不需要很多输出。

通常,第一个字符串只是查找第二个

的参数

输入:

    ...

config 'wan'
    data 'a1 a2 a3'
    something 'words'

config 'lan'
    info 'words'
    data 'b1 b2 b3'
    something 'words'

config 'net'
    something 'words'
    info 'words'
    data 'c1 c2'

    ...

输出:

b1 b2 b3

---编辑: -

我相信,通过此表单的输入将更广泛的脚本功能:

输入:

    ...

config something 'wan'
    something some_data 'a1 a2 a3'
    something 'words'

config something 'lan'
    something some_info 'words'
    something some_data 'b1 b2 b3'
    something 'words'

config something 'net'
    something 'words'
    something some_info 'words'
    something some_data 'c1 c2'

    ...

注意请求,这里有更好的解释:

1 - 找到'lan'的行(或者可能是config。*。'lan')

2 - 如果找到,请在第一行搜索以下行,其中包含单词结束数据(可能是* .data)

3 - 在此行的''之间打印内容

输出:

b1 b2 b3

什么是最佳解决方案?

感谢关注!

4 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

awk -v C="lan" -v F="data" '$1=="config" { gsub(/^[\47"]|[\47"]$/,"",$2); conf=$2; next } conf==C && $1==F { $1=""; gsub(/^ *[\47"]|[\47"]$/, ""); print }' YOURFILE

输入:

config 'wan'
    data 'a1 a2 a3'
    something 'words'

config 'lan'
    info 'words'
    data 'b1 b2 b3'
    something 'words'

config 'net'
    something 'words'
    info 'words'
    data 'c1 c2'    

输出:

b1 b2 b3

更新问题的方法略有不同:

awk -v C="lan" -v F="data" 'BEGIN { FS="\47"; REG=".*"F"[ \t]*" } $1~"config[ \t]" { conf=$2 } conf==C && $1~REG { print $2 }' YOURFILE

输入:

config something 'wan'
    something some_data 'a1 a2 a3'
    something 'words'

config something 'lan'
    something some_info 'words'
    something some_data 'b1 b2 b3'
    something 'words'

config something 'net'
    something 'words'
    something some_info 'words'
    something some_data 'c1 c2'

输出:

b1 b2 b3

答案 1 :(得分:1)

$ awk '
BEGIN {
    RS=""                      # empty RS separates record by empty lines
    FS=" *\47[\n ]*"           # FS is a single quote surrounded by space and \n
}
match($0,"config" FS "lan") {  # if record has proper config line
    for(i=1;i<=NF;i+=2)        # iterate keys
        if($i=="data")         # if data found
            print $(i+1)       # print its value
}' file
b1 b2 b3

答案 2 :(得分:1)

使用,您可以将RS设置为空字符串,并将每一行设置为字段,方法是将FS设置为新行。

parse.awk

BEGIN {
  RS = ""
  FS = "\n"
  q  = "'"      # Convenient definition of the quote character
}

$1 ~ q c q {
  for(i=2; i<=NF; i++) {
    if( $i ~ /^ *data / ) {
      split($i, a, q)
      print a[2]
    }
  }
}

像这样运行:

awk -f parse.awk -v c=lan dims

输出:

b1 b2 b3

答案 3 :(得分:0)

使用gnu sed

cat sedscript

:A
/^config/!d
/lan/!d
:B
N
s/.*\n//
/^config/bA
/.*data[^']*/!bB
s///
:C
s/([^']*)(')([^']*.*)/\1\3/
tC
p
bB

你称之为

sed -nEf sedscript infile
相关问题