How do I place commas between fields?
Input data
12123 \'QA test case 1\' \'QA environment\'
12234 \'UAT test case 1\' \'UAT environment\'
>
A naïve bash
implementation that assumes that no (escaped) '
instances ever appear inside a field:
Input is assumed to come from file file
:
# Read all whitespace-separated tokens (potentially across quoted field boundaries).
while read -ra tkns; do
# Initialize per-line variables.
numTkns=${#tkns[@]} i=0 inField=0
# Loop over all tokens.
for tkn in "${tkns[@]}"; do
# Determine if we're inside a quoted field.
[[ $tkn == \'* ]] && inField=1
[[ $tkn == *\' ]] && inField=0
# Determine the output separator:
if (( ++i == numTkns )); then
sep=$'\n' # last token, terminate output line with \n
else
# inside a field: use just a space; between fields: use ', '
(( inField )) && sep=' ' || sep=', '
fi
# Output token and separator.
printf '%s%s' "$tkn" "$sep"
done
done < file