separate fields by comma using bash

前端 未结 8 1436
滥情空心
滥情空心 2021-01-25 01:07

How do I place commas between fields?

Input data

12123 \'QA test case 1\' \'QA environment\'   
12234 \'UAT test case 1\' \'UAT environment\'  
         


        
8条回答
  •  旧时难觅i
    2021-01-25 01:44

    A naïve bash implementation that assumes that no (escaped) ' instances ever appear inside a field:

    • Original single-quoting is preserved.
    • Accepts any number of input fields.
    • Any fields may be single-quoted.
    • Caveat: whitespace between fields is normalized (replaced with a single space each), as is whitespace inside a quoted 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
    

提交回复
热议问题