Skip to content

Instantly share code, notes, and snippets.

@bycoffe
Forked from JoeGermuska/csvcut
Created September 14, 2009 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bycoffe/186819 to your computer and use it in GitHub Desktop.
Save bycoffe/186819 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Like cut, but for CSVs. To be used from a shell command line.
Note that fields are zero-based, as opposed to 'cut' where they are 1-based.
Leveraged from/motivated by an example from @bycoffe
Usage:
csvcut foobar.csv
(prints the first column of each row of foobar.csv)
head -10 foobar.csv | csvcut -f 0,2
(prints the first and third columns of the first ten lines of foobar.csv)
csvcut -f 0,2 -d "|" foobar.csv
(prints the first and third columns of the pipe-delimited foobar.csv)
"""
import sys, csv, getopt
opts, args = getopt.getopt(sys.argv[1:], "f:d:", ["fields=", "delimiter="])
if args:
i = open(args[0])
else:
i = sys.stdin
delimiter = ','
cols = [0, ]
if opts:
opts = dict(opts)
if '-f' in opts:
cols = opts['-f'].split(",")
if '-d' in opts:
delimiter = opts['-d']
for row in csv.reader(i, delimiter=delimiter):
for c in cols:
print row[int(c)],
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment