When managing configuration files, it is often necessary to distinguish between commented and un-commented lines. This guide will show you how to use the grep command to find and save commented and uncommented lines in a file.
Finding Commented Lines
Commented lines in a configuration file typically start with a #. You can use grep to search for these lines and save the output to a file.
Explanation:
- ^#: This pattern matches lines that start with #.
- /etc/crontab: The file being searched.
- > commented-lines: Redirects the output to a file named commented-lines.
Example Output:
[root@redhat ~]# grep ^[#] /etc/crontab > commented-lines
To view the saved output:
cat commented-lines
Preview:
[root@redhat ~]# cat commented-lines# Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed[root@redhat ~]#
Finding Uncommented Lines
Uncommented lines do not start with a #. You can use grep to search for these lines and save the output to a file.
Explanation:
- ^[^#]: This pattern matches lines that do not start with #.
- /etc/crontab: The file being searched.
- > un-commented-lines: Redirects the output to a file named un-commented-lines.
Example Output:
[root@redhat ~]# grep ^[^#] /etc/crontab > un-commented-lines
To view the saved output:
cat un-commented-lines
Preview:
[root@redhat ~]# cat un-commented-linesSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=rootFor details see man 4 crontabs[root@redhat ~]#
Summary
You can use the grep command to filter out commented and uncommented lines from a file and save the results to separate files. This is useful for quickly reviewing and managing configuration settings.
Finding and Saving Commented Lines:
grep ^[#] /etc/crontab > commented-lines
View saved output:
grep ^[^#] /etc/crontab > un-commented-lines
View saved output: