Ruby script that will invoke a command line command, for example ls -l, then take a specific column to feed to another fn

I want to create a ruby ​​script that I can run on the command line, which will be:

1. run a command line command like e.g.  "ls -l"
2. then I pass an argument for a specific column from the output of #1
3. for each column specified in #2, it will run another command

ls -l was just an example, I want this to be common.

I'm new to the ruby, still not getting some of this, so if you could praise what and how you did it, that would be very helpful to me.

+3
source share
1 answer

I often use |awk '{print $5;}'(replace 5with columns with one index of your choice) in pipelines. You can get similar simple single-line s rubyif you use a few funny command line switches. For comparison:

$ ls -l | awk '{print $5;}'

404
16
10
8733

against

$ ls -l | ruby -ne "a = split; puts a[4];"
nil
404
16
10
8733

ruby -n while gets() do .. end , ruby -e script . , , perl -ne awk(1).

manpage , :

 -a             Turns on auto-split mode when used with -n or
                -p.  In auto-split mode, Ruby executes
                      $F = $_.split
                at beginning of each loop.

, ( bash(1) $F[3] ).:

$ ls -l | ruby -ane 'puts $F[3]'
nil
root
root
root
root
sarnold
sarnold
...
+3

All Articles