Looping through a file, comparing lines


We occasionally get customers asking how to change or delete lines based on the existence of a string in a neighboring line. This usually means setting up a command file that does While loop processing. You can find a great example of a command file called Looper in the Qedit manual under the While command, but here is a variation that came up recently.

The customer wanted to print any lines in which the first 3 characters were the same as the previous line's. HPVariables can be used to store the value of each line for comparison to the next, but how can you set a variable to the contents of the line? We created the command file Qsetvar.Cmd to accept a variable name as a parameter, then prompt for the variable's value:

Qsetvar.Cmd:

    parm varname
    input !varname
    setvar !varname rtrim(!varname)
This way, the contents of a line can be saved in the Hold file, and the contents of the Hold file can be passed to the command file by means of I/O redirection:

    qsetvar myvar < hold
Our second command file saves the contents of each line, compares it to the next, then saves the contents of that line for comparison to the subsequent line, and so on:

    /set window (up)	     {ignore case for strings}
    setjcw cierror = 0	     {initialize variables to predictable values}
    setvar prev,"#"
    setvar curr," "
    continue
    /set right 3	     {edit only columns 1 to 3 of each line}
    /list first	             {go to top of file}
    while cierror=0 do
    /holdq *	             {copy current line to Hold file}
    /qsetvar  curr < hold    (set variable "curr" to whatever is in Hold}
    if prev = curr  then     {compare current line to previous}
    /list * lp	             {if same, send to printer}
    endif
    setvar  prev,curr	     {update value of prev}
    /lq*+1	             {move forward one line}
    endwhile

[Paul Gobes]

....Back to the Qedit Q&A Page