Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 views
in Technique[技术] by (71.8m points)

bash - Parsing the first column of a csv file to a new file

Operating System: OSX Method: From the command line, so using sed, cut, gawk, although preferably no installing modules.

Essentially I am trying to take the first column of a csv file and parse it to a new file.

Example input file

EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6

Desire output

EXAMPLEfoo 
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4

So I want the first column.

Here is what I have tried so far:

awk -F"," '{print $1}' in.csv > out.txt

awk -F"," '{for (i=2;i<=NF;i++)}' in.csv > out.txt

awk -F"," 'BEGIN { OFS="," }' '{print $1}' in.csv > out.txt

cat in.csv | cut -d , -f 1 > out.txt

None seem to work, either they just print the first line or nothing at all, so I would assume it's failing to read line by line.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your last option works perfectly for me:

$ cat > in.csv  # Then pasted the example input followed by Ctrl+D:
EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6
[Ctrl+D]
$ cat in.csv | cut -d, -f1
EXAMPLEfoo
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4

Maybe line endings are biting you here? If the file has DOS-style or even old-Mac-style line endings, this might cause strange behaviour. Try running file in.csv and see what it comes up with.

$ file in.unix.csv
in.unix.csv: ASCII text
$ file in.dos.csv
in.dos.csv: ASCII text, with CRLF line terminators

If the latter is your situation, use the dos2unix tool to convert the file.

Edit: On OS X, it seems flip is what you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...