separate fields by comma using bash

前端 未结 8 1421
滥情空心
滥情空心 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条回答
  •  孤独总比滥情好
    2021-01-25 02:06

    This solution (I believe) is not very nice, but standard at least:

    awk 'BEGIN{SP="[:space:]"}{gsub("(["SP"]*('\''[^'\'']*'\''|[^'\''"SP"])+)","&,");if(match($0, (",["SP"]+$")))$0=substr($0,1,RSTART-1)substr($0,RSTART+1)}1'
    

    Though some "broken" awk implementations don't support character classes with the [[:foo:]] style, in that case you can use:

    awk 'BEGIN{SP=" \t\f\v\r\n"}{gsub("(["SP"]*('\''[^'\'']*'\''|[^'\''"SP"])+)","&,");if(match($0, (",["SP"]+$")))$0=substr($0,1,RSTART-1)substr($0,RSTART+1)}1'
    

    Note: I used '\'' to place each single quote character because that's a simple and standard way to do it. If you want to use this line in a ".awk" file, just replace every occurrence with a single quote.

提交回复
热议问题