简体   繁体   English

使用cut将竖线分隔符转换为逗号分隔符

[英]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. 我有一个以竖线分隔的输入csv,我想从中选择几列,然后另存为以逗号分隔的文件。

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: 使用下面的代码,我可以读取输入的csv并将选定的列另存为新的csv,但是它仍然是管道分隔的:

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. 当我尝试使用output-delimiter选项时,出现非法选项错误。

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 ...]

My cut doesn't understand the --output-delimiter directive. 我的cut不了解--output-delimiter指令。 Are you sure that you have a version of cut that does? 您确定您有一个cut版本吗?

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 ,它可以理解输入和输出的不同字段分隔符:

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

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM