comma separated values to single inverted quote and comma separated values

前端 未结 4 421
自闭症患者
自闭症患者 2021-01-07 13:49

I have data as

    abc,defg,hijklm,op,qrs,tuv

I want this data to be converted to

    \'abc\',\'defg\',\'hijklm\',\'op\',         


        
4条回答
  •  借酒劲吻你
    2021-01-07 14:07

    Add a single quote at start (^) & end ($), and replace comma by quote-comma-quote (like you did) using sed with 3 expressions (using -e option to specify them):

    echo  abc,defg,hijklm,op,qrs,tuv | sed -e "s/^/'/" -e "s/\$/'/" -e "s/,/',\'/g" 
    

    (also: protect single quotes with double quotes)

    results in:

    'abc','defg','hijklm','op','qrs','tuv'
    

    in awk (maybe a little clumsy), generally better since field parsing is handled natively by awk:

    echo  abc,defg,hijklm,op,qrs,tuv | awk -F, "{for (i=1;i<=NF-1;i++) printf(\"'%s',\",\$i); printf(\"'%s'\",\$i);}"
    

    (print all fields plus comma except for the last one)

提交回复
热议问题