动态填充多维awk数组

贾斯汀

我正在研究解析文件的Awk / Gawk脚本,为每行填充一个多维数组。第一列是一个以句点分隔的字符串,每个值都是对下一级数组键的引用。第二列是值

这是被解析的内容的示例:

$ echo -e "personal.name.first\t= John\npersonal.name.last\t= Doe\npersonal.other.dob\t= 05/07/87\npersonal.contact.phone\t= 602123456\npersonal.contact.email\t= john.doe@idk\nemployment.jobs.1\t= Company One\nemployment.jobs.2\t= Company Two\nemployment.jobs.3\t= Company Three"
personal.name.first     = John
personal.name.last      = Doe
personal.other.dob      = 05/07/87
personal.contact.phone  = 602123456
personal.contact.email  = john.doe@idk
employment.jobs.1       = Company One
employment.jobs.2       = Company Two
employment.jobs.3       = Company Three

在解析之后,我希望它具有与以下相同的结构:

data["personal"]["name"]["first"]     = "John"
data["personal"]["name"]["last"]      = "Doe"
data["personal"]["other"]["dob"]      = "05/07/87"
data["personal"]["contact"]["phone"]  = "602123456"
data["personal"]["contact"]["email"]  = "[email protected]"
data["employment"]["jobs"]["1"]       = Company One
data["employment"]["jobs"]["2"]       = Company Two
data["employment"]["jobs"]["3"]       = Company Three

我坚持的部分是如何在构建多维数组时动态填充键。

我发现这个SO线程涵盖了一个类似的问题,通过使用SUBSEP变量可以解决该问题,起初它看起来像我需要的那样,但是经过一些测试,看起来好像arr["foo", "bar"] = "baz"并没有像真正的数组那样处理,例如一样arr["foo"]["bar"] = "baz"我的意思是不能在数组的任何级别中计算值的一个例子:arr["foo", "bar"] = "baz"; print length(arr["foo"])只会打印一个0(零)

我发现此SO线程会有所帮助,可能会指出正确的方向。

在提到的线程片段中:

BEGIN {
  x=SUBSEP

  a="Red" x "Green" x "Blue"
  b="Yellow" x "Cyan" x "Purple"

  Colors[1][0] = ""
  Colors[2][0] = ""

  split(a, Colors[1], x)
  split(b, Colors[2], x)

  print Colors[2][3]
}

是非常接近的,但我现在遇到的问题是,关键词(例如:事实上RedGreen等)需要动态指定的,并且有可能是一个或多个键。

基本上,我怎样才能将a_keysb_keys字符串分开,用分割.,然后将ab变量填充为多维数组?

BEGIN {
  x=SUBSEP

  # How can I take these strings...
  a_keys = "Red.Green.Blue"
  b_keys = "Yellow.Cyan.Purple"

  # .. And populate the array, just as this does:
  a="Red" x "Green" x "Blue"
  b="Yellow" x "Cyan" x "Purple"

  Colors[1][0] = ""
  Colors[2][0] = ""

  split(a, Colors[1], x)
  split(b, Colors[2], x)

  print Colors[2][3]
}

任何帮助,将不胜感激,谢谢!

埃德·莫顿

所有你需要的是:

BEGIN { FS="\t= " }
{
    split($1,d,/\./)
    data[d[1]][d[2]][d[3]] = $2
}

看:

$ cat tst.awk
BEGIN { FS="\t= " }
{
    split($1,d,/\./)
    data[d[1]][d[2]][d[3]] = $2
}
END {
    for (x in data)
        for (y in data[x])
            for (z in data[x][y])
                print x, y, z, "->", data[x][y][z]
}

$ awk -f tst.awk file
personal other dob -> 05/07/87
personal name first -> John
personal name last -> Doe
personal contact email -> john.doe@idk
personal contact phone -> 602123456
employment jobs 1 -> Company One
employment jobs 2 -> Company Two
employment jobs 3 -> Company Three

当然,以上是特定于gawk的,因为没有其他awk支持真正的多维数组。

要在索引并非总是相同深度时(例如上面的3个)填充多维数组,则要复杂得多:

##########
$ cat tst.awk
function rec_populate(a,idxs,curDepth,maxDepth,tmpIdxSet) {
    if ( tmpIdxSet ) {
        delete a[SUBSEP]                # delete scalar a[]
        tmpIdxSet = 0
    }
    if (curDepth < maxDepth) {
        # We need to ensure a[][] exists before calling populate() otherwise
        # inside populate() a[] would be a scalar, but then we need to delete
        # a[][] inside populate() before trying to create a[][][] because
        # creating a[][] below creates IT as scalar. SUBSEP used arbitrarily.

        if ( !( (idxs[curDepth] in a) && (SUBSEP in a[idxs[curDepth]]) ) ) {
            a[idxs[curDepth]][SUBSEP]   # create array a[] + scalar a[][]
            tmpIdxSet = 1
        }
        rec_populate(a[idxs[curDepth]],idxs,curDepth+1,maxDepth,tmpIdxSet)
    }
    else {
        a[idxs[curDepth]] = $2
    }
}

function populate(arr,str,sep,  idxs) {
    split(str,idxs,sep)
    rec_populate(arr,idxs,1,length(idxs),0)
}

{ populate(arr,$1,",") }

END { walk_array(arr, "arr") }

function walk_array(arr, name,      i)
{
    # Mostly copied from the following URL, just added setting of "sorted_in":
    #   https://www.gnu.org/software/gawk/manual/html_node/Walking-Arrays.html
    PROCINFO["sorted_in"] = "@ind_str_asc"
    for (i in arr) {
        if (isarray(arr[i]))
            walk_array(arr[i], (name "[" i "]"))
        else
            printf("%s[%s] = %s\n", name, i, arr[i])
    }
}

##########
$ cat file
a uno
b,c dos
d,e,f tres_wan
d,e,g tres_twa
d,e,h,i,j cinco

##########
$ awk -f tst.awk file
arr[a] = uno
arr[b][c] = dos
arr[d][e][f] = tres_wan
arr[d][e][g] = tres_twa
arr[d][e][h][i][j] = cinco

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章