-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseCsvFunctions.sh
executable file
·62 lines (52 loc) · 1.78 KB
/
parseCsvFunctions.sh
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
55
56
57
58
59
60
61
62
#!/usr/bin/env bash
# Provides functions to parse strings in CSV format.
# Note: This script was generated by Chat-GPT after some messages back and forth:
# https://chat.openai.com/share/0bd3cde7-32d0-460d-830c-79b7d00a2492
# Fail on any error ("-e" = exit on first error, "-o pipefail" exist on errors within piped commands)
set -o errexit -o pipefail
# Function to get the value of a specific column in a CSV string
# that only consists of a header line with the column names and a second line of values.
#
# Parameters:
# $1: CSV string (two lines)
# $2: Column name
get_csv_column_value() {
csv_string="$1"
column_name="$2"
# Remove leading and trailing double quotes, and spaces
csv_string=$(echo "$csv_string" | sed 's/"//g' | tr -d ' ')
# Extract header and values
header=$(echo "$csv_string" | head -n 1)
values=$(echo "$csv_string" | tail -n 1)
# Convert comma-separated strings into arrays
IFS=', ' read -r -a header_array <<< "$header"
IFS=', ' read -r -a values_array <<< "$values"
# Find the index of the column
index=-1
for i in "${!header_array[@]}"; do
if [ "${header_array[$i]}" = "$column_name" ]; then
index="$i"
break
fi
done
if [ "$index" -eq -1 ]; then
echo "Error: Column '$column_name' not found"
exit 1
else
# Print the value at the corresponding index
echo "${values_array[$index]}"
fi
}
# Function to get the value of a specific column in a CSV string and check if its greater than zero.
#
# Parameters:
# $1: CSV string (two lines)
# $2: Column name with a numeric value
is_csv_column_greater_zero() {
columnValue=$(get_csv_column_value "${@}")
if [[ "${columnValue}" -gt 0 ]]; then
true;
else
false;
fi
}