Unix - combine all rows into a comma-separated single row

后端 未结 2 1065
逝去的感伤
逝去的感伤 2021-02-06 19:42

I have following values in a file in separate lines:
California
New York
Washington
South Carolina
Kansas

What would be unix script to disp

相关标签:
2条回答
  • 2021-02-06 20:00

    Use this command tr '\n' ',' < input_file

    For single quotes use sed -e "s/^/'/" input_file | sed -e "s/$/'/" | tr '\n' ','

    (Not tested for single/double quote escaping issues)

    For variable NEW_VAR=$(echo $VAR | sed -e "s/^/'/" | sed -e "s/$/'/" | tr '\n' ',')

    0 讨论(0)
  • 2021-02-06 20:09

    You need to use awk to format the output. Does sed and awk ring a bell?

    The file <test.txt>
    California
    New York
    Washington
    South Carolina
    Kansas
    

    $ grep input file | awk '{print}' ORS=', '

    California, New York, Washington, South Carolina, Kansas
    

    Then concatenate your string and look out for the proper output.

    with awk you can try this

    sudo awk -F'\n' '{if(NR == 1) {printf "\x27" $0 "\x27"} else {print "," "\x27" $0 "\x27"}}' test.txt
    
    'California','New York','Washington','South Carolina','Kansas'
    

    You can also try this

    sudo awk 'BEGIN {RS=""}{gsub(/\n/,"\x27,\x27",$0); print $0}' test.txt
    
    0 讨论(0)
提交回复
热议问题