2 ms·
Ruby and Perl has the -n switches to provide that boilerplate. E.g Ruby: ruby -nae 'print $.," ",$F[1],"\n" if $_ =~ /^[A-Za-z]/' -n wraps an implicit "wh
by vidarh 3y ago
Ruby and Perl has the -n switches to provide that boilerplate. E.g Ruby:
ruby -nae 'print $.," ",$F[1],"\n" if $_ =~ /^[A-Za-z]/'
-n wraps an implicit "while gets; ... ;end" around the code; "-a" adds an implicit "$F = $_.split" at the start of the loop; "-" takes an expression from the command line; $_ contains the result of the `gets`; $. contains the line number of the last line read.
Alternatively:
ruby -ne '$_.match(/^[A-Za-z]+(.*)/) { puts "#{$.}#{$1}" }'
`match` sets $1, $2 etc to the corresponding capture group, and calls the block if successful.
The scaffolding would be easy to provide w/Python too, but the extra Awk/Perl-isms to make it convenient is another matter (and while I use them occasionally for one-liners, I will get shouty if I find $1 etc. in production code...).
Even the Ruby differences are sufficient extra noise that I still reach for awk for simple stuff like that.