我有一个配置文件,我需要删除以 # 开头到行尾的注释。 但它不应该影响双引号/单引号中的值。
我的输入文件:
# 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/