Comma quibbling: Difference between revisions

→‎{{header|UNIX Shell}}: There's already an AWK solution under that language; replace the one here with a solution using only builtins
(→‎{{header|UNIX Shell}}: There's already an AWK solution under that language; replace the one here with a solution using only builtins)
Line 4,547:
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{trans|AWK}}
{{works with|Korn Shell}}
<syntaxhighlight lang="bash">quibble() {
{{works with|Z Shell}}
# Here awk(1) is easier than sed(1).
<syntaxhighlight lang="bash">quibble() {
awk 'BEGIN {
quibble() {
for (i = 1; i < ARGC - 2; i++) s = s ARGV[i] ", "
printf '{'
i = ARGC - 2; if (i > 0) s = s ARGV[i] " and "
i = ARGC - 1; ifwhile (i( $# > 0)2 s = s)); ARGV[i]do
printf "{'%s}\n", s' "$1"
shift
exit 0
done
}' "$@"
if (( $# )); then
}
printf '%s' "$1"
shift
fi
if (( $# )); then
printf ' and %s' "$1"
fi
printf '%s\n' '}'
}</syntaxhighlight>
 
With a slight modification, it will work in any POSIX shell, or even older Bourne-compatible shells as long as they have functions and <b>printf</b>:
 
<syntaxhighlight lang="sh">
quibble() {
printf '{'
while [ $# -gt 2 ]; do
printf '%s, ' "$1"
shift
done
if [ $# -gt 0 ]; then
printf '%s' "$1"
shift
fi
if [ $# -gt 0 ]; then
printf ' and %s' "$1"
fi
printf '%s\n' '}'
}</syntaxhighlight>
 
The test code is the same either way:
<syntaxhighlight lang="sh">
quibble
quibble ABC
1,481

edits