grep Extensive Examples
Great. I’ll gather a comprehensive set of grep command examples for searching the AOSP (Android Open Source Project) codebase. This will include:
Searching for Java/Kotlin class names and filenames
Filtering by specific directories (e.g.,
frameworks/base)Finding usage references of classes or methods
Using case-insensitive, recursive searches
Common and useful regular expression (regex) patterns in context
I’ll format it clearly with explanations for each command and organize it by use case for easy reference.
Searching the AOSP Codebase with grep: A Practical Guide
grep: A Practical GuideWhen working with the Android Open Source Project (AOSP), the codebase is vast (hundreds of thousands of files). Using grep effectively can help locate definitions and references quickly. This guide provides practical grep command examples for common tasks, with explanations and notes on the results. (Note: If you have run AOSP’s build setup script, there are convenience commands like jgrep for Java, ktgrep for Kotlin, etc., which simply wrap grep with file-type filters (AOSP Tips | CppCoder). Here, we show the general grep usage for clarity.)
1. Searching for Java and Kotlin Class Definitions
Often you need to find where a class is defined (which file contains its declaration). In AOSP, Java class names usually match their filename (e.g. ActivityManagerService is in ActivityManagerService.java). We can search for the class <Name> declaration in the source files:
Java Class Definition: To find where a Java class is declared, search for the
classkeyword followed by the class name, restricting to Java files. For example, to locate theActivityManagerServiceclass definition in the frameworks code:grep -R "class ActivityManagerService" --include="*.java" frameworks/baseNotes: This recursively (
-R) searches under frameworks/base for lines containing “class ActivityManagerService” in files ending with.java. It will output the file path and the matching line. In this case, you should see a line in frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java (the class declaration) confirming the file that defines the class.Kotlin Class Definition: For Kotlin classes, use a similar approach with
.ktfiles. For example, to find theAlarmActivityclass in the DeskClock app (if it’s written in Kotlin):grep -R "class AlarmActivity" --include="*.kt" packages/apps/DeskClockNotes: This looks in packages/apps/DeskClock for “
class AlarmActivity” in any.ktfile. The result will show the Kotlin file (e.g. AlarmActivity.kt) and the line where the class is defined. This helps you locate the file quickly.
Tip: If you only remember part of a class name, you can search just that substring. For example,
grep -R "AlarmActivity" .(with or without theclasskeyword) will find any mention of “AlarmActivity” in the codebase. However, including theclasskeyword or a space before the name often narrows the results to the class declaration itself. You can also use the-loption to list only filenames: for instance,grep -R -l "AlarmActivity" .will output the path of any file that contains “AlarmActivity” (useful to quickly see the file name that likely matches the class).
2. Limiting Search to Specific Directories
The AOSP tree is organized into subprojects (frameworks, packages, hardware, etc.). You can focus your grep search on a particular directory to reduce noise. Simply specify the directory path in the grep command:
Framework-only Search: For example, to search within the core framework code (the frameworks/base directory) for occurrences of “BatteryService”:
Notes: This searches recursively in frameworks/base only. The output will list matches in that directory (e.g. lines in services/core/java/com/android/server/BatteryService.java and possibly references in SystemServer.java that start the service). By limiting the scope, you ignore irrelevant results from other parts of AOSP.
Packages (Apps) Search: Similarly, to search only within the AOSP apps (under packages/apps). For instance, to find where any system app calls
WifiManager.setWifiEnabled(...):Notes: This scans all apps for the string
setWifiEnabled(, which is a method call to enable Wi-Fi. The results will show which app source files call this method (for example, the Settings app might callsetWifiEnabledto toggle Wi-Fi). Focusing on packages/apps means you won’t see framework internal references, only usage in app code.
You can target multiple directories by listing them in the command. For example, to search both frameworks and packages: grep -R "MediaPlayer" frameworks/base packages/apps. Conversely, to exclude a directory, use the --exclude-dir option. For example, add --exclude-dir="out" or .git to skip build output or VCS files if needed.
3. Finding Usage References (Classes and Methods)
To understand how a class or method is used, you can grep for its name across the codebase:
Class Usage: If you want to find all references to a class (e.g. where the class is mentioned or used), search by the class name. For accuracy, it helps to match it as a whole word so you don’t get partial matches. For example, to find usages of
PowerManager(the API class for power management) across AOSP:Notes: The
-wflag matches whole words, so it will find “PowerManager” but not “PowerManagerService” or “mPowerManager” (which have extra characters attached). The search (here on.meaning the current directory, presumably the root of AOSP) will return lines wherePowerManageris referenced. This can include import statements, variable declarations (PowerManager pm = ...), or method calls on aPowerManagerinstance. From the output, you’ll see file paths – for instance, references in frameworks/base/services/ (system server usage) and in packages/apps/ (apps obtaining aPowerManagerto manage wake locks).Method Usage: To find where a specific method is called, include
(in the search to target the call syntax. For example, to find who callscheckSelfPermission(...)(the runtime permission check method) in the AOSP apps:Notes: This will list all places under packages/apps where
checkSelfPermission(appears (likely in activities or services that check permissions). Each result shows the file and line of the call. Including the parenthesis ensures you’re seeing the method invocation (or definition) rather than mentions of the name in comments or documentation. In this case, most hits will be actual calls in app code; the method’s definition (in the Android framework Context class) might also appear once. You can ignore the definition if you’re only interested in usage. If needed, refine the search by including a class name or context (e.g., grep for"pm.checkSelfPermission("if you only want cases where aPackageManager pmvariable is used).
Tip: When searching for usage, sometimes you want to exclude the class’s own definition or irrelevant matches. You can do this by combining greps. For example, to find usages of
SomeClassoutside its declaration, you might dogrep -R "SomeClass" . | grep -v "class SomeClass", which filters out the line that defines the class. Another option is to use the-Lflag (capital “L”) to find files not containing a pattern, but piping to a secondgrep -v(invert match) is straightforward.
4. Case-Insensitive Searches
Sometimes the exact casing of a term is unknown or inconsistent (for example, acronyms or words in log messages). grep -i makes the search case-insensitive, matching any case combination. In AOSP, this is useful for searching XML tags, intent actions, or strings that might appear in upper or lower case.
Example – Intent Action: Android intent actions are often upper-case with dots (e.g.
ANDROID.INTENT.ACTION...in documentation) but in code they might appear lower-case or mixed. If you want to find where the action"android.intent.action.SERVICE_STATE"is mentioned in the source, you can search case-insensitively:Notes: This will find any mention of that intent action in AndroidManifest.xml files, ignoring case differences (Android Protected Broadcasts – Crashpost). In this case, it’s targeting manifest files because broadcast intent names are typically declared there. The output will show which manifest files contain that action (for example, in the Phone app or frameworks base). The
-iflag ensures that even if the case in the file differs (e.g. all lower-case vs upper-caseSERVICE_STATE), it will be matched.Example – General Case Insensitivity: As another example, consider searching for references to Bluetooth. The word “Bluetooth” might appear capitalized (class names like
BluetoothAdapter), uppercase (constants likeBluetoothAdapter.STATE_ON), or lowercase (in comments or XML). Using-iallows one command to find all forms:Notes: This will catch Bluetooth in any case. You might see results like BluetoothAdapter.java, which contains the class
BluetoothAdapter(capital B), as well as occurrences of “bluetooth” in XML resource files or logs. Case-insensitive search is helpful when you're unsure of the exact capitalization or when searching human-readable text.
Keep in mind that case-insensitive searches can return more results than you need, so use them when case variations are a possibility. If you know the exact case (e.g. class names in Java are case-sensitive and usually consistently capitalized), you can omit -i to narrow the matches.
5. Recursive Searches across the Codebase
By default, grep examines one file at a time and does not search directories recursively unless you specify a recursive option. In a codebase like AOSP, you will almost always want to search recursively through directories. The -R (or -r) flag enables recursive search. Most examples above use -R already, but here are a couple of notes:
Entire Tree Search: To search the entire AOSP tree from the root, run grep
-Ron.(current directory) or on the root path. For instance:Notes: This will traverse all subdirectories, looking for “CameraService”. The output could be lengthy, as it will include the class definition (probably in frameworks/base/services for the camera service) and any references in other modules. Use this broad search when you aren’t sure where something is defined or used. (Be prepared for it to take a few seconds, as AOSP is large (AOSP: Advanced Development Tricks - inovex GmbH).)
Skipping Binary Files: When searching the whole tree, you might encounter binary files (prebuilt
.jarlibraries, images, etc.) that could produce “Binary file matches” messages (Developer essentials: How to search code using grep | MDN Blog). To avoid this, use-I(capital i) to ignore binaries. For example:Notes:
-Itells grep to treat binary files as having no matches, so the output will only show text file results. This is useful in AOSP since directories likeprebuilts/or.git/contain binary data. You can also explicitly exclude known binary-containing directories with--exclude-dir, as mentioned earlier.
In summary, always include -R (recursive) when you want to search through directories of code (Developer essentials: How to search code using grep | MDN Blog). You can combine it with other options (-n for line numbers, -i for case, etc.) as needed. In fact, it’s common to run grep -Ri <pattern> . as a reflex when searching code (Developer essentials: How to search code using grep | MDN Blog), meaning “search recursively, case-insensitively, for this pattern here.”
6. Using Regex Patterns for Partial Names and CamelCase
One of grep’s strengths is the ability to use regular expressions (with the -E flag for extended regex or by default in most modern grep). This is very handy in AOSP for matching partial identifiers or patterns like CamelCase words. Below are some common regex use-cases:
Partial Matches with Wildcards: If you only remember parts of a name or want to match a family of names, you can use
.*in a regex pattern to represent “any characters in between.” For example, suppose you recall a class name had “Audio” and ended with “Manager” but not the full name. You can search:Notes: The
-Eenables extended regex so we can use.*(any characters) easily. This will find lines likeclass AudioManageras well asAudioDeviceManagerorAudioProfileManager– basically any occurrence of “Audio” followed later by “Manager” on the same line (Developer essentials: How to search code using grep | MDN Blog). The results might include class declarations or references. For instance, it will match thepublic class AudioManagerdeclaration and any code references likeAudioManager am = .... If you intended to only catch class names, you might refine the regex to ensure “Manager” comes at the end of a word (see next point).Matching Word Boundaries (CamelCase exact names): To avoid matching substrings inside longer names, you can use word boundary anchors or the
-woption. For regex,\brepresents a word boundary. For example, to match exactly “NetworkPolicyManager” (and not things like “NetworkPolicyManagerService”), you could use:Notes: This pattern uses
\bto ensure the term is a whole word. In GNU grep, this works with-E(extended regex) for word characters. An easier alternative is using-was shown earlier. These ensure that your partial search is precise. In practice,grep -R -w "NetworkPolicyManager" .would yield only exact matches of that identifier.Alternation (OR patterns): Extended regex allows using
|to search for multiple patterns in one pass. For example, if you want to find references to either of two related classes (sayActivityManagerorActivityManagerService), you could do:Notes: The pattern
ActivityManager(Service)?will match “ActivityManager” or “ActivityManagerService” (the()?makes “Service” optional). This single command finds both terms. Similarly,grep -R -E "Foo|Bar" .would find occurrences of either “Foo” or “Bar”. Using one grep with alternation can be more efficient than running two separate greps (Developer essentials: How to search code using grep | MDN Blog).CamelCase component search: CamelCase names have transitions from lowercase to uppercase. If you want to search by one part of a camelCase name, you can just grep that substring (CamelCase doesn’t require special handling since grep sees it as a normal string). However, you can craft regex if needed. For example, to find methods that start with "get" followed by a capital letter (typical Java getter naming convention):
Notes: This searches in frameworks/base for lines where “get” is followed by an uppercase letter and then one or more letters, and an open parenthesis – essentially method names like getData(), getUserId(), etc. This is a more advanced regex usage, demonstrating how to target a pattern (here, method naming). The output will include any getter method calls or definitions in that directory. This kind of pattern matching can help when you know the naming convention but not the full name.
In most cases, simpler is better: use .* for unknown in-between text or use -w to restrict whole words. Regex is powerful but can also over-match. Test your pattern on a smaller scope if possible. Grep’s extended regex mode (-E) must be used for operators like | or + – otherwise, escape them or use grep -P for Perl-compatible regex if really complex (though -P is not always available by default).
7. Additional Tips and Tools
Reading the Output: Grep results are of the form
path/to/file:matched line. If you want line numbers, add-n. If the output is too long, you can pipe tolessor another pager. For example:grep -R "FooBar" . | less -R(the-Rin less preserves color highlights).Performance Consideration: Grepping the entire AOSP can take a while (several seconds per query) because of the huge number of files (AOSP: Advanced Development Tricks - inovex GmbH). If you find yourself doing this often, consider using faster search tools. ripgrep (
rg) and The Silver Searcher (ag) are popular alternatives that work similarly to grep but are optimized for speed. In one comparison on AOSP,rgwas about 15× faster than GNU grep (AOSP: Advanced Development Tricks - inovex GmbH) for a large search, andagabout 7× faster. They support the same regex patterns and options (often with slightly different syntax conventions), and search recursively by default. These tools can significantly boost productivity when exploring large codebases.AOSP Code Search: Google also provides an online search interface called Android Code Search (cs.android.com) which can be useful for quick lookups without downloading the source. However, when working locally with the code, mastering
grep(or its faster cousins) is invaluable for quick searching.
Using the above techniques, you should be able to quickly locate file names, class definitions, and references within the AOSP source. By combining flags like -R (recursive), -i (ignore case), and -E (regex), you can handle a wide range of search scenarios in one command (Developer essentials: How to search code using grep | MDN Blog). Happy grepping!
Sources:
Brian Smith, “Developer essentials: How to search code using grep,” MDN Blog (Jul 3, 2023) – Basics of recursive grep and regex usage (Developer essentials: How to search code using grep | MDN Blog) (Developer essentials: How to search code using grep | MDN Blog).
Crashpost, “Android Protected Broadcasts,” (Jan 11, 2014) – Example of using grep with
-r -iand--includeto find intent strings in AOSP (Android Protected Broadcasts – Crashpost).Stefan Lengfeld, “AOSP: Advanced Development Tricks,” inovex blog (Sept 15, 2021) – Notes on grep performance and alternatives for the AOSP codebase (AOSP: Advanced Development Tricks - inovex GmbH) (AOSP: Advanced Development Tricks - inovex GmbH).
Thomas Yuan, “AOSP Tips,” CppCoder (Oct 15, 2020) – List of AOSP environment grep aliases like jgrep, mgrep, etc. (AOSP Tips | CppCoder).
Last updated