我的数据如下:
a, 1
a, 2
a, 3
b, 4
b, 5
b, 6
我想使用bash命令以下面的形式实现它:
a, "[1, 2, 3]"
b, "[4, 5, 6]"
带引号和方括号的东西并不相关,因为在第二列中只有第一列中具有相同值的项目集合。
答案 0 :(得分:0)
a, 1
a, 2
a, 3
b, 4
b, 5
b, 6
#! /bin/bash
set -o errexit # Exit if there is an error
form=${1?"Expected form as argument"}
while read -r line; do
cmd="${line/,[[:space:]]/+=(})"; # replace line with "var+=(val)"
eval ${cmd}; # Process the command, add the value to the array.
done < "${form}"
while read -r array; do
eval echo "${array} [\${$array[@]}]"; # Should print array (val val val)
done < <(cut -f1 -d"," "${form}" | sort | uniq) # Get all the array names
这个脚本应该做你想要的。
答案 1 :(得分:0)
绝对无效(您应该使用awk
或perl
)
file="file.txt"
while read -r k
do
printf '%s, "[%s]"\n' "$k" "$(paste -sd, <(grep -oP "^$k\s*,\s*\K.*" "$file"))"
done < <(cut -d, -f1 "$file" | sort -u)
输出:
a, "[1,2,3]"
b, "[4,5,6]"