在包含特定单词的行之后获取字符串

Get string after a line with a certain word

对于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

最佳解决方案是什么?

感谢关注!

您可以使用类似的东西:

awk -v C="lan" -v F="data" '=="config" { gsub(/^["]|["]$/,"",); conf=; next } conf==C && ==F { =""; gsub(/^ *["]|["]$/, ""); 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=""; REG=".*"F"[ \t]*" } ~"config[ \t]" { conf= } conf==C && ~REG { print  }' 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
$ awk '
BEGIN {
    RS=""                      # empty RS separates record by empty lines
    FS=" *[\n ]*"           # FS is a single quote surrounded by space and \n
}
match([=10=],"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

使用 ,您可以通过将 RS 设置为空字符串将每个部分视为一条记录,通过将 FS 设置为 new-line 将每一行视为一个字段。

parse.awk

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

 ~ 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

使用 gnu sed

cat sedscript

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

你就这样称呼它

sed -nEf sedscript infile