-
Notifications
You must be signed in to change notification settings - Fork 1
/
sparql-query.sh
executable file
·89 lines (79 loc) · 2.49 KB
/
sparql-query.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/bash
endpointSelect="http://data.dm2e.eu:9997/dm2e-direct/sparql"
prefixFile="prefixes.rq"
outputFormat="tsv"
declare -A initialBindings
echoerr() { echo $@ 1>&2; }
showUsage() {
echo "sparql-query <queryFile> [Options]"
echo ""
echo "Arguments:"
echo ""
echo " <queryFile> File containing the SPARQL query, REQUIRED"
echo ""
echo "Options:"
echo ""
echo " --endpoint <endpoint> SPARQL endpoint to query [Default: '$endpointSelect']"
echo " --prefixes <prefixfile> Load SPARQL Prefixes from prefixfile [Default: '$prefixFile']"
echo " --format <tsv|xml|json|ntriples> Format for displaying the result bindings [Default: '$outputFormat']"
echo " --bind <var> <val> Replace all occurences of ?val by the value"
echo " (to parameterize the query) REPEATABLE"
}
urlencode() {
echo "$1" | curl -Gso /dev/null -w %{url_effective} --data-urlencode @- "" | cut -c 3-
}
parseOpts() {
if [[ -z $1 ]];then
showUsage
exit 2
fi
queryFile=$1
shift;
while [[ ! -z $1 ]];do
case $1 in
"--endpoint")
endpointSelect=$2;
shift ; shift
;;
"--prefixes")
prefixFile=$2;
shift ; shift
;;
"--format")
outputFormat=$2;
shift ; shift
;;
"--bind")
local varName=$2
local varVal=$3
initialBindings["$varName"]=$varVal
shift ; shift ; shift
;;
*)
showUsage
exit 1
;;
esac
done
}
# Parse command line options
parseOpts $*
# create unformatted query by concatenating prefixes and query file sans comments
queryUnformatted=$(cat $prefixFile $queryFile | grep -v '^\s*#')
# Initialize with initial bindings
for bindingName in ${!initialBindings[@]};do
bindingValue=${initialBindings["$bindingName"]}
# echoerr "Binding $bindingName to $bindingValue"
queryUnformatted=$(echo "$queryUnformatted" | sed "s,\?$bindingName\b,$bindingValue,g")
done
echoerr $queryUnformatted
# URL Encode
queryFormatted=$(urlencode "$queryUnformatted")
# Send request
if [[ $outputFormat = "ntriples" ]];then
url="${endpointSelect}?query=${queryFormatted}"
curl -H "Accept: application/n-triples" $url
else
url="${endpointSelect}?format=${outputFormat}&query=${queryFormatted}"
curl $url
fi