Convert text file into a comma delimited string

前端 未结 5 686
南旧
南旧 2021-02-06 17:25

I don\'t seem to locate an SO question that matches this exact problem.

I have a text file that has one text token per line, without any commas, tabs, or quotes. I want

5条回答
  •  我在风中等你
    2021-02-06 18:14

    Tested the four approaches on a Linux box - Bash only, paste, awk, Perl, as well as the tr | sed approach shown in the question:

    #!/bin/bash
    
    # generate test data
    seq 1 10000 > test.file
    
    times=${1:-50}
    
    printf '%s\n' "Testing paste solution"
    time {
        for ((i=0; i < times; i++)); do
          csv_string=$(paste -sd, test.file)
        done
    }
    
    printf -- '----\n%s\n' "Testing pure Bash solution"
    time {
        for ((i=0; i < times; i++)); do
          csv_string=$(

    Surprisingly, the Bash only solution does quite poorly. paste comes on top, followed by tr | sed, Awk, and perl:

    Testing paste solution
    
    real    0m0.109s
    user    0m0.052s
    sys 0m0.075s
    ----
    Testing pure Bash solution
    
    real    1m57.777s
    user    1m57.113s
    sys 0m0.341s
    ----
    Testing Awk solution
    
    real    0m0.221s
    user    0m0.152s
    sys 0m0.077s
    ----
    Testing Perl solution
    
    real    0m0.424s
    user    0m0.388s
    sys 0m0.080s
    ----
    Testing tr | sed solution
    
    real    0m0.162s
    user    0m0.092s
    sys 0m0.141s
    

    For some reasons, csv_string=${csv_string//$'\n'/,} hangs on macOS Mojave running Bash 4.4.23.


    Related posts:

    • How to join multiple lines of file names into one with custom delimiter?
    • Concise and portable “join” on the Unix command-line
    • Turning multi-line string into single comma-separated

提交回复
热议问题