Use grep to Search IBM i Source Members (RPG, CL, COBOL, more)

From the Seiden SmartSupport mailbag:

One issue I keep coming across is the inability to search for text in source members across all libraries. We use a commercial tool, but it is expensive and cumbersome. Coming from the Linux world, where I can “grep” for anything, I find this a ridiculous restriction.

You can, indeed, search source members for text using grep.

December 2024 Update

Try our improved “Physical File Grep (PFGREP)” command instead of the commands below. It is faster and more reliable than QShell grep for searching source code. A more detailed article is on the way.

Original version of the article follows:

Use the correct grep command

To search source members, it’s important to use Qshell’s version of grep, which understands native EBCDIC encoding. In other words, instead of the standard PASE version (/QOpensys/pkgs/bin/grep), use /usr/bin/grep instead.

How to grep for text

Let’s say you want to find out where RPG calls PHP. Grep can search for the string “php” (case-insensitive) inside RPG source members.

From QShell (called from a traditional 5250 IBM i command line):

QSH

Then search for our desired text (“php” in our case) using grep:

/usr/bin/grep -i -n "php" /QSYS.LIB/*.LIB/QRPG*.FILE/*.MBR

From Bash shell

If you are in a bash shell, rather than Qshell, you need a slightly more complex command so that Qshell still processes the output. The command from bash should look like this:

echo "/usr/bin/grep -i -n "php" /QSYS.LIB/*.LIB/QRPG*.FILE/*.MBR" | qsh

With our server, here are some of the results:

Each search result above includes:

  • Full path to the source member
  • Line number where the string was found
  • The line itself. Because we used grep’s -i option, the results were case insensitive; that is, PHP, Php, and php all matched.

Thanks to Liam Allan for his assistance with this tip.

January 2024 Update

Since the original 2023 publication of this post, both Simon Hutchinson and Richard Schoen have published code to run grep source code searches from traditional ILE and 5250 environments. We thank them for their work and recommend people check it out:

 

9 replies
  1. Nelson Carta Martinez
    Nelson Carta Martinez says:

    It’s very interesting. However I have some problems: The example, as it is, does not work in V7R4 but in general it does the job. In V7R5 it works perfectly (as indicated in the article)

    Reply
    • Alan Seiden
      Alan Seiden says:

      Hi, Nelson, thanks for your comment. We’ve successfully tested this technique on an IBM i 7.4 system, so I don’t think the OS level is the problem. Let us know if you can identify some other difference.

      Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.