Skip to content

Instantly share code, notes, and snippets.

@janderudder
Last active October 9, 2021 10:50
Show Gist options
  • Save janderudder/bffc7aa8dee2e6d13ed5a171e60670dc to your computer and use it in GitHub Desktop.
Save janderudder/bffc7aa8dee2e6d13ed5a171e60670dc to your computer and use it in GitHub Desktop.
Print all fields line by line. Sorta like cut but knows only one column and outputs all fields.
#!/bin/bash
Base="$(basename -s'.sh' "$0")"
Help()
{
cat <<!
Print all fields line by line.
Usage:
\$ $Base [-d'DELIMITER'] [-q'QUOTE'] STRING
\$ $Base [--delim 'DELIMITER'] [--quote 'QUOTE'] STRING
DELIMITER (optional)
The delimiter to use for parsing and separating elements inside the
string. Default = IFS.
QUOTE (optional)
If provided, each element will be quoted when output.
Default = no quote.
STRING
The text that will be parsed according to DELIMITER.
DELIMITER and QUOTE may be provided using long or short form of the option.
In short form there should be no space between the switch and the value,
whereas there should be one with long form.
Not specifying the delimiter may lead to unexpected output in some cases.
!
}
HelpMessage()
{
echo "Type $Base --help for information."
}
# parse help
for Arg in "$@"
do
case "$Arg" in '--help'|'-h'|'-help'|'--h')
Help
exit 0
esac
done
# check args
if [[ $# -lt 1 ]]
then
echo 'Need at least one argument.'
HelpMessage
exit 1
fi
# globals
declare -A Option=([delim]=$IFS [quote]='')
declare Target=''
# utils for options
SetOpt()
{
Option[$1]="$2"
}
SetShortOpt()
{
SetOpt $1 "${2:2:${#2}}"
}
# parse arguments
while [[ $# -ne 0 ]]
do
if [[ "$1" =~ ^-q.*$ ]]; then
SetShortOpt quote "$1"
elif [[ "$1" == '--quote' ]]; then
shift
SetOpt quote "$1"
elif [[ "$1" =~ ^-d.*$ ]]; then
SetShortOpt delim "$1"
elif [[ "$1" == '--delim' ]]; then
shift
SetOpt delim "$1"
elif [[ "$1" == '--' ]]; then
shift
Target="${@}"
break
else
Target="${@}"
break
fi
shift
done
# edge case checking
if [[ -z $Target ]]
then
echo 'No string to parse.'
HelpMessage
exit 1
fi
# parse input
IFS="${Option[delim]}" Arr=($Target)
# output
if [[ -n ${Option[quote]} ]]
then
declare -r Quote="${Option[quote]}"
for Elem in "${Arr[@]}"
do
echo "${Quote}${Elem}${Quote}"
done
else
for Elem in "${Arr[@]}"
do
echo "$Elem"
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment