I think this has yet to be one of the most exciting things to learn recently. It’s the power of grep-ing things. When I learned this, I legit feel like I just acquired a superpower. It saves so much time and energy, and it helps you in so many situations.
Grep is a command that you can use to find and print lines in files that match a certain pattern. Can be confusing a bit if this is your first time, but let’s take a look at the real case below so we can understand how it works.
For instance, today, a client has a huge error_log and he asked me to retrieve logs that come from July 2022 only. I wish I can just open the log, copy them manually, and share the logs from July 2022 only. However, Jesus Christ, it was a 1GB log. My terminal would have gone dead trying to open the file, and it’s not efficient as well downloading it manually to your local device. Thanks to Grep command, though. I can save so much time and acquire the necessary logs only within seconds.
That being said, let’s dive in further and learn this superpower together.
Here’s the basic command:
grep [filename] [string]
Let’s say you have an error log called error_log and I would only need the log that comes from the date 14-Apr-2022. Here’s the command that I would use:
It would return with a line that contains the string “14-Apr-2022”:
[14-Apr-2022 20:30:51 UTC] WordPress database error Table 'mdm9paz_gopf.wp_wpmailsmtp_tasks_meta' doesn't exist for query SHOW FULL COLUMNS FROM `wp_wpmailsmtp_tasks_meta` made by require_once('wp-load.php'), require_once('wp-config.php'), require_once('wp-settings.php'), do_action('init'), WP_Hook->do_action, WP_Hook->apply_filters, WPMailSMTP\Core->get_tasks, WPMailSMTP\Tasks\Tasks->init, WPMailSMTP\Tasks\Reports\SummaryEmailTask->init, WPMailSMTP\Tasks\Task->register, WPMailSMTP\Tasks\Meta->add, WPMailSMTP\Tasks\Meta->add_to_db
Even better, you can export the result into a text file by simply adding “> [filename].txt” by the end of the command. For instance, this command will export the same exact result to a text file called error_log_14-Apr.txt:
grep error_log 14-Apr-2022 > error_log_14-Apr.txt
Cool amirite? Imagine not having to go through all the error_logs when you only want to find a certain string, and you’ll be able to instantly compile them in a text file. All you need to do is to modify the command with the filename and the string, and that’s it!