As a programmer, you will not only have to work with your own code, but code written by others.
Maintaining and updating other's code is quite challenging even if it is well-written.
There are tools that can make this easier.
Using a search tool is essential for dealing with unfamiliar code. "grep" is a powerful UNIX search tool. It has the following usage:
grep [flags] pattern files
To find all of the class statements in all java files, we could use:
grep class *.java
Some of grep's more useful flags:
Invert match (show lines that don't have the pattern given.
Give line numbers of matches.
Search recursively (in all subdirectories).
We can also chain multiple searches together with pipes. To search for all lines that have "class" but not "public" we could do:
grep class *.java | grep -v "public"
The pattern given to grep does not have to be an exact string, it can be a regular expression. These can match more complicated searches
grep allows the following special characters
The beginning of the line.
The end of the line.
Any single character in the brackets such as [abc] or [0-9].
Any single character except those in brackets
Any one character.
Match zero or more of the preceding characters.
If we want to search for one of the special characters, we can "escape it" by preceding it with a backslash.
grep is for searching the contents of files. If you want to search for files by name, you can use the find command.
The basic form of find is:
So if we want to find a particular file starting in the current directory, we could use:
find "start-location" -name pattern
If we wanted to find all java files, we could use:
find . -name "File.java"
find . -name *.java
cscope is a program for searching through source code across directories. It was written for C, but also works with C++ and Java.
To use cscope, we need to tell it what files to scan. They should be listed in a file called "cscope.files" This can be done with the command:
find . -name "*.java" > cscope.files
Then we can run the command "cscope". We can search for symbols, definitions, test, regular expressions and see what functions call or are called by others.
You can use the tab key to switch between the results and search area. Selecting a result will open it in your $EDITOR.
Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.