RHCSA Practical Lab Series β Searching for Strings in a File
π 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! π