SkillSprout
Chapter 1 · Lesson 9
Beginner
1 min read

Search Text with grep and find

Overview

Use grep to search text inside files or streams and find to search filesystem entries by name, type, size or modification time. The tools answer different questions and do not search the same kind of input.

Detailed Notes

Search file contents

bash
grep "error" /var/log/syslog
grep -i "error" app.log
grep -n "timeout" app.log
grep -R "database" ~/linux-practice
  • -i ignores case.
  • -n prints line numbers.
  • -R recursively searches directories.
  • -w matches a complete word.

Exit status:

  • 0 means one or more matches.
  • 1 means no matches.
  • 2 means an error occurred.

Search filenames

bash
find . -type f -name "*.log"
find /var/www -type f -mtime -7
find . -type d -name "backup"
  • -type f matches regular files.
  • -type d matches directories.
  • -name matches filenames.
  • -mtime -7 means changed less than seven 24-hour periods ago.

Run an action for results

bash
find . -type f -name "*.tmp" -print
find . -type f -name "*.tmp" -delete

Run -print first and verify every result. -delete removes matches without a separate rm confirmation.

Common Interview Questions

Finished this lesson?

0 of 25 lessons done · 0% of the course