Skip to content

Instantly share code, notes, and snippets.

@ekeyme
Last active January 13, 2017 10:13
Show Gist options
  • Save ekeyme/652cf5fe4ce1540d74d9cbab68125600 to your computer and use it in GitHub Desktop.
Save ekeyme/652cf5fe4ce1540d74d9cbab68125600 to your computer and use it in GitHub Desktop.
joining contents in line with strings
#!/usr/bin/env bash
#
# MIT license
# Author: EKEYME@GMAIL.COM
#
# joining contents in line with strings
short_usage="$(basename $0) [-h] [join_string] [left-closer [right-closer]]"
# display usage
usage() {
cat <<EOF
usage: $short_usage
Joining contents in line with strings from <stdin>.
-h, --help show this help message and exit
join_string join string, used to replace the new line
closer closer string, used to close the whole joined string
EOF
}
if [[ $1 == -h || $1 == --help ]]; then
usage
exit
fi
if (($# > 3)); then
echo "usage: $short_usage" >&2
echo "$(basename $0): error: arguments should no more than 3" >&2
exit 1
fi
if (($# == 0)); then
join_string="','"
lcloser="'"
rcloser="'"
elif (($# == 1)); then
join_string=$1
lcloser=""
rcloser=""
elif (($# == 2)); then
join_string=$1
lcloser=$2
rcloser=$2
else
join_string=$1
lcloser=$2
rcloser=$3
fi
exec 3< <(tac | tac)
read -u3 line
if (($? == 1)); then
exit
fi
printf "%s" "$lcloser"
while true; do
read -u3 current_line
if (($? == 1)); then
printf "%s%s" "$line" "$rcloser"
break
else
line=${line%$'\r'}
printf "%s%s" "$line" "$join_string"
fi
line=$current_line
done
echo
exec 3<&-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment