【问题标题】:Store specific fields of a file as the values in an associative array bash将文件的特定字段存储为关联数组 bash 中的值
【发布时间】:2015-10-22 00:44:44
【问题描述】:

有一个文件看起来像这样:

f1.1 f2.1 f3.1 f4.1
f1.2 f2.2 f3.2 f4.2
f1.3 f2.3 f3.3 f4.3

然后我使用第 1 列作为关联数组中的键:

declare -A arr=(); while read -r a b; do arr["$a"]="$b"; done <file

打印键和值的结果:

for K in "${!arr[@]}"; do
    echo $K --- ${arr[$K]}
done

f1.1 --- f2.1 f3.1 f4.1
f1.2 --- f2.2 f3.2 f4.2
f1.3 --- f2.3 f3.3 f4.3

如果我只想将第 2 列和第 3 列存储为值怎么办?这样上面的命令给出:

f1.1 --- f2.1 f3.1
f1.2 --- f2.2 f3.2
f1.3 --- f2.3 f3.3

【问题讨论】:

    标签: bash shell associative-array


    【解决方案1】:

    取决于您的需求,但我会做一些awk 魔术:

    # will print:
    # f1.1 --- f2.1 f3.1
    # f1.2 --- f2.2 f3.2
    # ...
    awk '{print $1" --- "$2" "$3}' file
    

    您也可以将 awk 与 bash 混合使用:

    declare -A arr=(); 
    while read -r a b; do 
      rr["$a"]="$(echo $b | awk '{print $1" "$2}')" 
    done < file
    

    【讨论】:

    • 我的意思是从关联数组中打印键/值的结果是“col1 --- col2 col3”,而不是直接从文件中打印?或者换句话说,关联数组只存储“col2 col3”作为值而不是“col2 col3 col4”希望这是有道理的
    • arr["$a"]="$(echo $b|awk '{print $1" "$2}')" :D ?
    猜你喜欢
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2017-02-26
    相关资源
    最近更新 更多