How to print the line number of the file I'm working with through ARGV?

I am currently opening a file received at runtime via ARGV:

File.open(ARGV[0]) do |f| f.each_line do |line| 

Once a match is found, I print the output to the user.

 if line.match(/(strcpy)/i) puts "[!] strcpy does not check for buffer overflows when copying to destination." puts "[!] Consider using strncpy or strlcpy (warning, strncpy is easily misused)." puts " #{line}" end 

I want to know how to print the line number for the corresponding line in the file (ARGV [0]).

Using print __LINE__ shows the line number from the Ruby script. I tried many different print __LINE__ with various line interpolations #{line} without success. Is there a way to print the line number from a file?

+6
source share
1 answer

When the Ruby IO class opens a file, it sets the global variable $. equal to 0. For each row that is read, this variable is incremented. So, to find out which line was read, just use $. .

Check out the English module $. or $INPUT_LINE_NUMBER .

We can also use the lineno method, which is part of the IO class. I find this a bit more confusing because we need an input / output stream object to bind it, while $. will always work.

I would write a loop more simply:

 File.foreach(ARGV[0]) do |line| 

Something to think about if you are on a * nix system, you can use the built-in grep or fgrep to speed up processing. The grep family of applications is highly optimized to do what you want and can find all occurrences, only the first can use regular expressions or fixed strings and can be easily called using Ruby %x or backtick statements.

 puts `grep -inm1 abacus /usr/share/dict/words` 

What outputs:

 34:abacus 

-inm1 means "ignore case of characters", "line numbers of output", "stop after first occurrence"

+9
source

Source: https://habr.com/ru/post/955227/


All Articles