RHCSA Practical Lab Series – Searching for Strings in a File

Expertise in Cloud, Networking & DevOps
Photo by MichaΕ‚ Kubalczyk / Unsplash

πŸ” Lab 11: Extracting Specific Lines from a File

πŸ“Œ Objective

In this lab, you will:

βœ” Search for lines containing a specific string (error) in a given file
βœ” Redirect the results into a separate output file (/root/errors.log)
βœ” Ensure the output preserves the exact formatting of the original file


πŸ“Œ Step 1: Locate the Target File

πŸ”Ή Confirm that the file exists before performing the search:

[root@node1 ~]# ls -l /var/log/messages

πŸ“Œ Explanation:

  • /var/log/messages β†’ Common system log file containing various events.
  • Ensure the file exists before proceeding.

βœ… If the file exists, proceed to Step 2.


πŸ“Œ Step 2: Search for a Specific String (error)

πŸ”Ή Use grep to find lines containing error in /var/log/messages:

[root@node1 ~]# grep error /var/log/messages

πŸ“Œ Explanation:

  • grep error /var/log/messages β†’ Displays all lines that contain the string "error".

πŸ”Ή Redirect the output to a new file (/root/errors.log) for future reference:

[root@node1 ~]# grep error /var/log/messages > /root/errors.log

πŸ“Œ Explanation:

  • > /root/errors.log β†’ Saves the output to /root/errors.log instead of displaying it on the screen.

βœ… Now, all matching lines are stored in /root/errors.log.


πŸ“Œ Step 3: Verify the Output

πŸ”Ή View the contents of /root/errors.log to confirm the extracted lines:

[root@node1 ~]# cat /root/errors.log

πŸ“Œ Expected Output (example):

Mar 28 12:34:56 node1 kernel: [123456.789] error: disk failure detected
Mar 28 12:35:01 node1 sshd[2501]: error: Authentication failed
...

βœ… If lines containing error appear, the extraction was successful.

πŸ“Œ Troubleshooting:

If /root/errors.log is empty, confirm that the original file contains error messages:

[root@node1 ~]# grep -i error /var/log/messages

(Use -i to make the search case-insensitive.)


βœ… Final Summary

βœ” Used grep to extract lines containing error from /var/log/messages
βœ” Stored the extracted lines in a separate output file (/root/errors.log)
βœ” Verified the output to ensure correct extraction


πŸ“Œ Next Lab: Archiving and Compressing Files with tar and bzip2

πŸ“© Subscribe for more RHCSA exam labs and hands-on tutorials! πŸš€


Read more