将数组中的两列存储为元素 - >密钥使用awk

时间:2016-03-08 22:08:13

标签: arrays bash awk

假设我的文件data.log包含以下内容:

[12/Mar/2015] /var/lib/file1.txt
[12/Mar/2015] /var/lib/file2.txt
[12/Mar/2015] /var/lib/file3.txt

如何使用awkbash将此文件的内容存储到一个数组中,其中[12/Mar/2015]是元素,/var/lib/fileN.txt是其关键字?

2 个答案:

答案 0 :(得分:4)

击:

# the data
$ cat data.log
[12/Mar/2015] /var/lib/file1.txt
[12/Mar/2015] /var/lib/file2.txt
[12/Mar/2015] /var/lib/file3.txt

# the associative array declaration
$ declare -A map

# read the data from the file into the array
$ while read -r date file; do map[$file]=$date; done < data.log

# iterate through the data
$ for key in "${!map[@]}"; do printf "%s => %s\n" "$key" "${map[$key]}"; done
/var/lib/file3.txt => [12/Mar/2015]
/var/lib/file2.txt => [12/Mar/2015]
/var/lib/file1.txt => [12/Mar/2015]

答案 1 :(得分:1)

在awk中:

$ awk '{map[$2]=$1}END{for(key in map){printf "%s => %s\n",key,map[key]}}' infile
/var/lib/file2.txt => [12/Mar/2015]
/var/lib/file3.txt => [12/Mar/2015]
/var/lib/file1.txt => [12/Mar/2015]

或者,作为非单行代表:

# For each line, use the second field as key and the first field as value
{
    map[$2] = $1
}

END {
    # Iterate over all keys
    for (key in map) {
        printf "%s => %s\n", key, map[key]
    }
}

这会进入一个文件,例如script.awk,然后用

调用
awk -f script.awk infile