Linux下批量删除配置文件中的注释和空行或只输出去除注释的

2021-12-02 1131点热度 0人点赞 0条评论

有的配置文件是很长的,例如redis的配置文件,其实主要原因是有些配置文件的注释很多,如果你对配置文件的注释不感兴趣,或者你很了解配置的含义,或者你只想要看实际的配置,可以试试如下做法:

输出去除注释的行

还是以redis.conf为例,注释是#开头的(大部分的配置文件注释都是#开头的),做法如下(这种方式不会修改愿配置文件的,只是输出):

使用grep命令

# 输出 redis.conf 中不包含注释的行,这种情况下,可能空行也显示出来了
grep -v '^#' /path/to/redis.conf

# 输出 redis.conf 中不包含注释的行,不要输出空行 grep .就是去除空行用的
grep -v '^#' /path/to/redis.conf | grep .

使用sed命令

# 显示除去注释的内容
sed '/^#/d' /path/to/redis.conf
sed '/#/d'  /path/to/redis.conf

# 显示除去空行的内容
sed '/^$/d' /path/to/redis.conf

如果是ini文件,注释是用;开头的,那么这样做:

grep ^[^\;] /path/to/php.ini

修改文件,去除注释或/和空行

  • 刚才grep的内容,可以重定向到一个新文件
# 去除注释后,生成一个新的文件 new_redis.conf
grep -v '^#' /path/to/redis.conf > /path/to/new_redis.conf

grep -v '^#' /path/to/redis.conf | grep . > /path/to/new_redis.conf
  • 直接修改配置文件
修改文件前,请备份源文件
# 修改前先备份
cp /path/to/redis.conf /path/to/redis.conf.bak

# 修改(删除注释)
sed -i '/#/d' /path/to/redis.conf

# 修改(删除空行)
sed -i '/^$/d' /path/to/redis.conf

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论