perl - 删除注释而不影响配置文件中的值

标签 perl awk

我有一个配置文件,我需要删除以 # 开头到行尾的注释。 但它不应该影响双引号/单引号中的值。

我的输入文件:

# comment1
# comment2
#hbase_table_name=mytable # hbase table.
hbase_table_name=newtable # hbase table.
hbase_txn_family=txn
app_name= "cust#100"  # Name of the application
app_user= 'all#50,all2#100'  # users
hbase.zookeeper.quorum=localhost
zookeeper.znode.parent=/hbase-secure
hbase.zookeeper.property.clientPort=2181

我正在尝试的 perl 命令

perl -0777 -pe ' s/^\s*$//gms ; s/#.*?$//gm; s/^\s*$//gms;s/^$//gm' config.txt

我得到的输出是

hbase_table_name=newtable
hbase_txn_family=txn
app_name= "cust
app_user= 'all
hbase.zookeeper.quorum=localhost
zookeeper.znode.parent=/hbase-secure
hbase.zookeeper.property.clientPort=2181

但是需要的输出是

hbase_table_name=newtable
hbase_txn_family=txn
app_name= "cust#100"
app_user= 'all#50,all2#100'
hbase.zookeeper.quorum=localhost
zookeeper.znode.parent=/hbase-secure
hbase.zookeeper.property.clientPort=2181

我正在寻找使用任何工具的 bash 解决方案 - awk 或 perl 可以解决这个问题。

一种罕见的情况可能是像这样的配置条目

app_user= 'all#50,all2#100'  # users - "all" of them

结果应该是 app_user= 'all#50,​​all2#100'

最佳答案

这是一个 perl 脚本:

#!/usr/bin/perl

use strict;

while (<DATA>){
    if (m/^\h*#/) {next;};
    if (m/((['"])[^\2]*\2)/) {print substr $_, 0, @+[0]; print "\n"; next; }
    s/#.*$//; print ;
}

__DATA__
# comment1
# comment2
#hbase_table_name=mytable # hbase table.
hbase_table_name=newtable # hbase table.
hbase_txn_family=txn
app_name= "cust#100"  # Name of the application
#app_name= "cust#100"  # Name of the application
app_user= 'all#50,all2#100'  # users
hbase.zookeeper.quorum=localhost
zookeeper.znode.parent=/hbase-secure
hbase.zookeeper.property.clientPort=2181
# from comments, other lines
hbase_table_name=newtable ## hbase table.
app_user= 'all#50,all2#100'  # users - "all" of them

输出:

hbase_table_name=newtable 
hbase_txn_family=txn
app_name= "cust#100"
app_user= 'all#50,all2#100'
hbase.zookeeper.quorum=localhost
zookeeper.znode.parent=/hbase-secure
hbase.zookeeper.property.clientPort=2181
hbase_table_name=newtable 
app_user= 'all#50,all2#100'

更改 <DATA><>并在文件上使用...

关于perl - 删除注释而不影响配置文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61369316/

相关文章:

perl - 我应该使用哪个框架来编写模块?

regex - URL 正则表达式不起作用

windows - 如何在重复分隔符处分割大型文本文件,而不是按行号或确切大小

awk - 如何使用 AWK 在 Begin 语句中定义动态数组

awk - 使用 awk 打印某些列不匹配的行

r - 在 Rmarkdown 中执行 Perl 6 代码

linux - perl脚本中的chown命令用法

regex - 合并行落在之间但不包括 sed 的重复模式

linux - 如何在mailx命令中添加收件人姓名

regex - 为什么命令行中 s/g 的以下变体是错误的?