separate fields by comma using bash

前端 未结 8 1417
滥情空心
滥情空心 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
    闹比i (楼主)
    2021-01-25 01:43

    Your input data looks very much like an argument list. Therefore, one convenient approach would be to define a bash function that simply returns its argument list as comma separated tokens and invoke that for each line in your file.

    However, the simple implementation below will lose the quotes around the multi-word tokens (but it will place the commas properly). If you need those quotes exactly as they were, it would get a bit more complicated (it's very easy to output every token quoted though):

    #!/bin/bash
    function csv_args() {
        while [ -n "$1" ]; do
            echo -n "$1"
            shift
            [ -n "$1" ] && echo -n ', '
        done
        echo
    }
    
    while read line; do
        eval csv_args $line
    done < /path/to/your/file
    

提交回复
热议问题