-
-
Save zdennis/036decee352a892030f3201e473a2518 to your computer and use it in GitHub Desktop.
shell script: grab
This file contains hidden or 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 | |
if STDIN.tty? | |
def print_help | |
puts <<-EOT.gsub(/^\s+\|/, '') | |
|Usage: ls | grab <column number> | |
| grab <column number> < INFILE | |
| grab <column number> <column number2> <column number3> ... < INFILE | |
| | |
|grab outputs a specific column of content from STDIN. | |
| | |
| column number - the numeric index of the column you want | |
| to output. This is 1-based Not 0-based. | |
| | |
|Example #1: Grabbing the filename from ls -l | |
| ls -l | grab 9 | |
| | |
|Example #2: Grabbing the list of modified file names in your Git index | |
| git status | grep modified: | grab 3 | |
| | |
|Example #3: Grabbing multiple columns | |
| ls -l | grab 1 9 | |
| | |
|Author: Zach Dennis ([email protected], [email protected]) | |
| http://www.continuousthinking.com | |
| http://www.mutuallyhuman.com | |
EOT | |
end | |
if ["-h", "--help"].include?(ARGV.first) | |
print_help | |
exit 0 | |
else | |
print_help | |
exit 1 | |
end | |
else | |
# we are 1-based, so convert to 0-based | |
columns = ARGV.map { |i| i.to_i - 1 } | |
arr = STDIN.readlines.map{ |line| | |
columns.map{ |column_index| | |
line.split(/\s+/)[column_index].to_s | |
} | |
} | |
maxlengths = [] | |
columns.each { |column_index| | |
arr.each { |data| | |
length = 0 | |
data.each_with_index { |cdata, i| | |
maxlengths[i] = cdata.length if cdata.length > length | |
} | |
} | |
} | |
arr.each do |data| | |
data.each_with_index do |cdata, i| | |
printf "%-#{maxlengths[i]}s\t", cdata | |
end | |
puts | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment