-
-
Save ybenjo/25cede44e6d3faee2d6c166847508804 to your computer and use it in GitHub Desktop.
cut with column names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# cat data.tsv | ccut -d delim -c name,name,name... | |
require 'trollop' | |
opts = Trollop::options do | |
opt :delim, 'delimitor', default: "\t" | |
opt :column, 'column name(s)', type: String | |
end | |
delim = opts[:delim] | |
column_names = opts[:column].split(',') | |
positions = [ ] | |
$<.each_with_index do |l, i| | |
ary = l.chomp.split(delim) | |
if i.zero? | |
header = [ ] | |
column_names.each do |c| | |
pos = ary.find_index(c) | |
unless pos.nil? | |
positions.push pos | |
header.push c | |
end | |
end | |
puts header.join(delim) | |
else | |
puts positions.map{|pos| ary[pos]}.join(delim) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment