This Blog is to share our knowledge and expertise on Linux System Administration and VMware Administration

Friday, January 5, 2018

Single command to take the backup and removes the commented and blank lines in a file

We can achieve by using 2 ways in Linux.

SED Command:

Normally, we will take back up and tidy the most of the configuration file. There is a tendency for many software packages to over comment their configurations. This can cause issues where you think that you have implemented a change; however, it was also set later on and you may not have noticed it.
Postfix, main.cf configuration file having 679 lines. We will back up the file so that we do not lose comments and documentations, but we will also have a new working file with less than 10 percent of the number of lines. The following command shows how this is done
[root@nsk etc]# cat /etc/postfix/main.cf | wc -l
679

[root@nsk etc]# sudo sed -i.bak '/^#/d;/^$/d' /etc/postfix/main.cf
Here:
#/d   - Remove the commented line
^$   - Remove the blank line

[root@nsk etc]# cat postfix/main.cf | wc -l
25
Above sed command reduces the file from 679 lines to 25 lines and is far easier to work with. We can now edit this file without any distractions. We will add two new lines and edit two existing lines to the /etc/postfix/main.cf file. This will need to be edited as root.

CAT Command:

We can use below command also to achieve the above output. 

[root@nsk etc]# [root@nsk postfix]# cat main.cf.bak | egrep -v "^#|^$" |tee -a main.cf_catoutput
[root@nsk postfix]# cat main.cf_catoutput | wc -l
25


Sed command will take the backup of existing file & the output will be saved in existing name. Here Cat command output will be saved in different name.

No comments:

Post a Comment