bash 如何从 CSV 文件中获取每一行的第一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11668621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:28:56  来源:igfitidea点击:

How to get the first column of every line from a CSV file?

bashshellcsvawktext-parsing

提问by Junba Tester

How do get the first column of every line in an input CSV file and output to a new file? I am thinking using awkbut not sure how.

如何获取输入 CSV 文件中每一行的第一列并输出到新文件?我正在考虑使用awk但不确定如何使用。

回答by Levon

Try this:

尝试这个:

 awk -F"," '{print }' data.txt

It will split each input line in the file data.txtinto different fields based on ,character (as specified with the -F) and print the first field (column) to stdout.

它将data.txt根据,字符(用 指定-F)将文件中的每个输入行拆分为不同的字段,并将第一个字段(列)打印到标准输出。

回答by Levon

Can be done:

可以做到:

$ cut -d, -f1 data.txt

回答by Nykakin

echo "a,b,c" | cut -d',' -f1 > newFile

回答by Debaditya

Input

输入

a,12,34
b,23,56

Code

代码

awk -F "," '{print }' Input

Format

格式

awk -F <delimiter> '{print $<column_number>}' Input

回答by kenorb

This can be achieved using grep:

这可以使用grep

$ grep -o '^[^,]\+' file.csv

回答by Chris Koknat

Using Perl:

使用 Perl:

perl -F, -lane 'print $F[0]' data.txt > data2.txt

perl -F, -lane 'print $F[0]' data.txt > data2.txt

These command-line options are used:

使用这些命令行选项:

  • -nloop around every line of the input file
  • -lremoves newlines before processing, and adds them back in afterwards
  • -aautosplit mode – split input lines into the @Farray. Defaults to splitting on whitespace.
  • -eexecute the perl code
  • -Fautosplit modifier, in this case splits on ,
  • -n循环输入文件的每一行
  • -l在处理之前删除换行符,然后将它们添加回
  • -a自动拆分模式 – 将输入行拆分到@F数组中。默认为在空白处拆分。
  • -e执行perl代码
  • -F自动拆分修饰符,在这种情况下拆分 ,


If you want to modify your original file in-place, use the -ioption:

如果要就地修改原始文件,请使用以下-i选项:

perl -i -lane 'print $F[0]' data.txt

perl -i -lane 'print $F[0]' data.txt



If you want to modify your original file in-place and make a backup copy:

如果要就地修改原始文件并制作备份副本:

perl -i.bak -lane 'print $F[0]' data.txt

perl -i.bak -lane 'print $F[0]' data.txt



If your data is whitespace separated rather than comma-separated:

如果您的数据是空格分隔而不是逗号分隔:

perl -lane 'print $F[0]' data.txt

perl -lane 'print $F[0]' data.txt