Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Linux上使用正则表达式替换文件中的多行文本_Python_Regex_Perl_Sed - Fatal编程技术网

Python 在Linux上使用正则表达式替换文件中的多行文本

Python 在Linux上使用正则表达式替换文件中的多行文本,python,regex,perl,sed,Python,Regex,Perl,Sed,我需要替换配置文件中的多行文本。 我可以使用sed(BusyBox v1.21.1)、perl(修订版5版本14 subversion 2)或python(2.7) 该文件可以有两种格式: (A) 或 (B) 我想把它改成这样: "is_managed": false, "local_profile_id": 15191724, "name": "First user" }, "session": { "restore_on_startu

我需要替换配置文件中的多行文本。 我可以使用sed(BusyBox v1.21.1)、perl(修订版5版本14 subversion 2)或python(2.7)

该文件可以有两种格式: (A)

或 (B)

我想把它改成这样:

     "is_managed": false,
      "local_profile_id": 15191724,
      "name": "First user"
   },
   "session": {
      "restore_on_startup": 4,
      "restore_on_startup_migrated": true,
      "urls_to_restore_on_startup": [ "http://192.168.0.100" ]
   }
}

可能您希望首先将其解析为json,并在需要时将其编码回json

use JSON::XS;

my $rh_data = decode_json($json_string);

#then updated values by accesing $rh_data->{xx}{yy} = 'new value';

#and encode back to json
$json_data  = encode_json($rh_data); 
while(我的$ln=){
如果($ln=~/^([]*)(\*\*)(.*)/){
打印“$1”。“$3”;
}elsif($ln=~/(.*)(\*\*)([]*)$/){
打印“$1”。“$3”;
}否则{
打印$ln;
}
}
试着把它当作
perl program.pl

您想要做的更改也是如此:从“会话”部分周围删除
*
,并将主机名转换为IP?这个列表中可能有很多主机名吗?在B)示例中,启动时没有
url\u to\u restore\u
条目,您希望发生什么?这看起来像JSON。是JSON吗?如果是JSON,您不想对正则表达式执行此操作。这只是为了删除
**
,我不确定您到底想要什么。但这只对其他注释中提到的
**
有帮助,若要将主机名解析为IP,您必须使用JSON解析器,如果它是JSON,还需要一些其他逻辑
     "is_managed": false,
      "local_profile_id": 15191724,
      "name": "First user"
   },
   "session": {
      "restore_on_startup": 4,
      "restore_on_startup_migrated": true,
      "urls_to_restore_on_startup": [ "http://192.168.0.100" ]
   }
}
use JSON::XS;

my $rh_data = decode_json($json_string);

#then updated values by accesing $rh_data->{xx}{yy} = 'new value';

#and encode back to json
$json_data  = encode_json($rh_data); 
while(my $ln = <STDIN>){
    if ($ln =~ /^([ ]*)(\*\*)(.*)/) {
        print "$1"."$3";
    } elsif ($ln =~ /(.*)?(\*\*)([ ]*)$/) {
        print "$1"."$3";
    } else {
        print $ln;
    }
}