Searching Output

Learning Outcome

Redirect the output of a program and use grep to search for strings.

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.

Applicable subjects

COMP1521, COMP2521, COMP3231


redirection

To redirect stdout into a file use:

$ ./<program> > <output_file>

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 "<string to search for>" <file_to_search_in>

The number of occurrences of a string can be found using:

$ grep -c "<string to search for>" <file_to_search_in>

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.

find_factors.c

find_factors.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {

    if (argc != 2) {
        printf("Program usage: ./find_factors <n>\n");
        return 1;
    }

    int n = atoi(argv[1]);
    int num_factors = 0;
    int i = 1;
    while (i <= n) {
        printf("%d", i);
        if (n % i == 0) {
            printf(" is a factor of %d", n);
        }
        printf("\n");
        i++;
    }

    printf("\nThere are %d positive factors of %d\n", num_factors, n);
    return 0;
}
$ 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.

Module author: Liz Willer <e.willer@unsw.edu.au>

Date

2020-02-13