Skip to content

Instantly share code, notes, and snippets.

@raypereda
Forked from juanje/gist:1310403
Created February 5, 2014 20:05
Show Gist options
  • Save raypereda/8831937 to your computer and use it in GitHub Desktop.
Save raypereda/8831937 to your computer and use it in GitHub Desktop.
# A few examples about how to use Ruby for parsing files as we could do
# with Awk or Grep. This is based on what I learn fro this post:
# http://code.joejag.com/2009/using-ruby-as-an-awk-replacement/
# Split each line with ':' and print the first $F[0] field
awk -F: '{ print $1 }' /etc/passwd
ruby -F: -nae 'puts $F[0]' /etc/passwd
# Parse the 'ps aux' output
# It'll print the ID process for the 'jojeda' user
ps aux | awk '$1 ~ /jojeda/ { print $2 }'
ps aux | ruby -nae 'puts $F[1] if $F[0] == "jojeda"'
# List of users with password
awk -F: '$2 ~ /[^!*]+/ { print $1 }' /etc/passwd
ruby -F: -nae 'puts $F[0] if $F[1] =~ /[^!*]+/' /etc/shadow
# From the original post:
# ‘-n’ makes the Ruby iterate over all lines successively assigning them to $_
# ‘-a’ makes Ruby split $_ into its parts assigning the result to $F which is an array of strings
# ‘-e’ means that what follows is code to be executed.
# ‘-F’ specifies the column separator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment