.. _log_files: ****************** Searching Output ****************** .. topic:: Learning Outcome Redirect the output of a program and use grep to search for strings. .. topic:: Introduction Output can be redirected to a file to be used in debugging using the symbol *>*. This is useful in cases where you want to refer to the output later or if there is a large amount of output. *grep* can be used to search through this file a specific string. .. topic:: Applicable subjects COMP1521, COMP2521, COMP3231 ---- redirection ============= To redirect stdout into a file use: :: $ ./ > This places all of the text that would normally appear on the terminal into the file specified. grep ========== To print out all occurrences of a string use: :: $ grep "" The number of occurrences of a string can be found using: :: $ grep -c "" ---- Example ======= This program finds the number of factors of a number n between 1 and n. However, when we run it, it says there are no factors. :download:`find_factors.c` .. literalinclude:: find_factors.c :language: c :linenos: :caption: find_factors.c :: $ gcc -Wall -Werror -std=c99 -o find_factors find_factors.c $ ./find_factors 1 is a factor of 20 2 is a factor of 20 3 4 is a factor of 20 5 is a factor of 20 6 7 8 9 10 is a factor of 20 11 12 13 14 15 16 17 18 19 20 is a factor of 20 There are 0 positive factors of 20 We can redirect the output to a log file using *>*: :: $ ./find_factors 20 > output.txt Then, we can search through the file with *grep* looking for the string "factor of": :: $ grep "factor of" output.txt 1 is a factor of 20 2 is a factor of 20 4 is a factor of 20 5 is a factor of 20 10 is a factor of 20 20 is a factor of 20 We can also count the number of times the string "factor of" appears: :: $ grep -c "factor of" output.txt 6 We seem to be finding the correct factors of 20, so we should check *num_factors*. Looking at the code, we realise that when we find the factors, we don't increment *num_factors*: :: int num_factors = 0; ... if (n % i == 0) { printf(" is a factor of %d", n); } ... This should be: :: int num_factors = 0; ... if (n % i == 0) { printf(" is a factor of %d", n); num_factors++; } ... While it may seem unnecessary to use redirection and grep in this instance where there are only 20 lines, it becomes far more necessary if we were finding the factors of 1024. Nobody wants to go through 1000+ lines of output. .. moduleauthor:: Liz Willer :Date: 2020-02-13