0008 Command_line

Ruby is also very comfortable in scripting mode. It can replace `sed`, `grep`, `awk`, ...

The -e option lets you specify the script directly as an argument.

One of the common features of the various utilities is line-by-line processing. Although it is possible to loop through the code, it is often more convenient to use the -n or -p option, which activates line-by-line processing.

0008-command_line_1.png

The documentation is very explicit on these 2 options!

-n assume 'while gets(); ... end' loop around your script

-p assume loop like -n but print line also like sed

Line-by-line processing relies on 2 special global variables and the default behavior of print:

  • $/ is the separator used to identify a ‘line’, defaulting to \n.
  • $_ contains the last ‘line’ read with gets. ⚠️ The separator is included in $_.
  • print with no argument displays the contents of the $_ variable.

Ex 1: Need to add a prefix to each line?

0008-command_line_2.png

Ex 2: Need to filter lines containing a 2? (Using slice!)

0008-command_line_3.png

Ex 3: Need to total up? (like awk Ruby has BEGIN and END blocks!)

0008-command_line_4.png

Last example where Ruby will be more enjoyable. Sort the words on each line in alphabetical order. You can even use the -a (autosplit) option to retrieve each column in another special global variable $F, thus acting even more like awk!

0008-command_line_5.png

Links to Ruby documentation for command line arguments, man and BEGIN / END (there’s an error in their example, can you see it?).