-
Notifications
You must be signed in to change notification settings - Fork 5
/
matrix
executable file
·54 lines (41 loc) · 1.53 KB
/
matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/bin/bash
# this script will take a space-separated file of the format:
# identifier value
# identifier value
# it will then store each 'value' in the array according to its identifier.
# so the lines: 'foo bar' 'foo baz' 'other thing' will be stored as
# values[foo,1]=bar; values[foo,2]=baz; values[other,1]=thing
# the second array 'counts' will keep track of how many values exist for each
# identifier. so counts[foo]=2; counts[other]=1.
# yes, it's 1-indexed. this is preference, but i find it easier to keep track of
###############################################################################
# set vars
file=/path/to/whatever
# requires bash >= 4.0. this declares the array as associative* (see notes)
declare -A values counts
# read the file line by line, splitting into fields based on space**
while read -r iden val; do
# increment 'counts' for the identifier
((counts[$iden]++))
# store the value in the array
values[$iden,${counts[$iden]}]=$val
done
# iterate over each identifier, dump the values. format will be:
# iden1: val1 val2
# iden2: val1 val2 val3
# loop over each identifier
for iden in "${!counts[@]}"; do
# print identifier
printf '%s:' "$iden"
# loop over 1 through counts[iden]
for ((i=1; i<=${counts[$iden]}; i++)); do
# print each value
printf ' %s' "${values[$iden,$i]}"
done
# print newline
echo
done
###############################################################################
# notes:
# * http://mywiki.wooledge.org/BashFAQ/006
# ** http://mywiki.wooledge.org/BashFAQ/001