Skip to content

Instantly share code, notes, and snippets.

@juanje
Created October 24, 2011 21:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save juanje/1310403 to your computer and use it in GitHub Desktop.
Save juanje/1310403 to your computer and use it in GitHub Desktop.
Use Ruby as AWK or Grep
# 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
@juanje
Copy link
Author

juanje commented Oct 24, 2011

My two new bash's alias:

alias rawk='ruby -nae'        # => awk
alias rawk:='ruby -F: -nae'   # => awk -F:

:-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment