Search code examples
bashdelimitercut

Using cut to Convert Pipe-Delimited to Comma-Delimited


I have an input csv that is pipe-delimited that I want to select a few columns from then save as a comma-delimited file.

Using the code below I can read the input csv and save the selected columns as a new csv, but it is still pipe-delimited:

cut -d "|" -f1-2,15,28-31,35 < input_file.csv > output_file.csv

when I try to use the output-delimiter option I get an illegal option error.

I tried:

cut -d "|" -f1-2,15,28-31,35 --output-delimiter="," < input_file.csv > output_file.cv

and

cut -d "|" -f1-2,15,28-31,35 < input_file.csv > output_file.csv --output-delimiter=","

But I get an error

cut: illegal option -- -
usage: cut -b list [-n] [file ...]
       cut -c list [file ...]
       cut -f list [-s] [-d delim] [file ...]

Solution

  • My cut doesn't understand the --output-delimiter directive. Are you sure that you have a version of cut that does?

    One idea is to first translate the | into ,, then cut that:

    tr '|' ',' < input_file.csv | cut -d ',' -f1-2,15,28-31,35 > output_file.csv
    

    Another option would be awk, which understands different field delimiters for input and output:

    awk 'BEGIN {FS="|"; OFS=","} 
               {print $1, $2, $15, $28, $29, $30, $31, $35}' \
         < input_file.csv >output_file.csv
    

    Cheers