Line Filters in COBOL

Here’s the translation of the Go line filter program to COBOL, formatted in Markdown for Hugo:

A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.

Here’s an example line filter in COBOL that writes a capitalized version of all input text. You can use this pattern to write your own COBOL line filters.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. LINE-FILTER.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT STANDARD-INPUT ASSIGN TO KEYBOARD
               ORGANIZATION IS LINE SEQUENTIAL.
           SELECT STANDARD-OUTPUT ASSIGN TO DISPLAY
               ORGANIZATION IS LINE SEQUENTIAL.
       DATA DIVISION.
       FILE SECTION.
       FD STANDARD-INPUT.
       01 INPUT-LINE PIC X(80).
       FD STANDARD-OUTPUT.
       01 OUTPUT-LINE PIC X(80).
       WORKING-STORAGE SECTION.
       01 WS-EOF PIC X VALUE 'N'.
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           OPEN INPUT STANDARD-INPUT
           OPEN OUTPUT STANDARD-OUTPUT
           PERFORM PROCESS-LINES UNTIL WS-EOF = 'Y'
           CLOSE STANDARD-INPUT
           CLOSE STANDARD-OUTPUT
           STOP RUN.

       PROCESS-LINES.
           READ STANDARD-INPUT
               AT END
                   MOVE 'Y' TO WS-EOF
               NOT AT END
                   PERFORM CAPITALIZE-LINE
                   WRITE OUTPUT-LINE
           END-READ.

       CAPITALIZE-LINE.
           MOVE FUNCTION UPPER-CASE(INPUT-LINE) 
               TO OUTPUT-LINE.

In this COBOL program:

  1. We define the input and output files as STANDARD-INPUT and STANDARD-OUTPUT, which correspond to stdin and stdout in other languages.

  2. We use a FILE SECTION to define the structure of our input and output lines.

  3. The main procedure opens the input and output, processes lines until we reach the end of the file, then closes the files.

  4. The PROCESS-LINES paragraph reads a line from the input. If it’s not the end of the file, it capitalizes the line and writes it to the output.

  5. The CAPITALIZE-LINE paragraph uses the COBOL intrinsic function UPPER-CASE to convert the input line to uppercase.

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > lines.txt
$ echo 'filter' >> lines.txt

Then use the line filter to get uppercase lines. Assuming your COBOL program is compiled into an executable named ’line-filter':

$ cat lines.txt | ./line-filter
HELLO
FILTER

Note that the exact command to run the COBOL program may vary depending on your COBOL compiler and operating system. You might need to set up the appropriate environment for file handling as well.