Linux 去除注释和空行

平时查看某些配置文件的时,我们会发现有很多注释(如:"#"开头的行),中间还有很多空行,看起来非常费劲,所以在这里总结下如何去除注释和空行的方法。

举例说明

这里选个简单点的文件,来演示下效果,我们可以看到一些空行和注释。

yum.conf 文件 内容

[root@centos115 ~]# cat /etc/yum.conf
[main]
cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=23&ref=http://bugs.centos.org/bug_report_page.php?category=yum
distroverpkg=centos-release


#  This is the default, if you make this bigger yum won't see if the metadata
# is newer on the remote and so you'll "gain" the bandwidth of not having to
# download the new metadata and "pay" for it by yum not having correct
# information.
#  It is esp. important, to have correct metadata, for distributions like
# Fedora which don't keep old packages around. If you don't like this checking
# interupting your command line usage, it's much better to have something
# manually check the metadata once an hour (yum-updatesd will do this).
# metadata_expire=90m

# PUT YOUR REPOS HERE OR IN separate files named file.repo
# in /etc/yum.repos.d
 

去除注释和空行的命令

  • 使用 tr命令

grep -v "#" /etc/yum.conf |tr -s '\n'

效果:

  • 使用 sed命令

grep -v "#" /etc/yum.conf|sed '/^$/d'

效果和上面一样,这里就不继续贴图了。

  • 使用 awk命令

grep -v "#" /etc/yum.conf |awk '{if($0!="")print}'

  • 使用 grep命令

grep -v "#" /etc/yum.conf |grep -v "^$"

命令分析:

每个命令的前面部分 grep -v "#" /etc/yum.conf ,意思是,查看/etc/yum.conf,过滤掉 # 开头的行,最后通过 “|” 管道 来继续执行去除空行命令。 

猜你喜欢

转载自blog.csdn.net/icanlove/article/details/41515019