在Linux上使用regex替换文件中的多行文本

时间:2021-01-21 12:15:36

I need to replace multiline text in config file. I can use sed (BusyBox v1.21.1), perl (revision 5 version 14 subversion 2) or python (2.7).

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

The file can have two formats: A)

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

     "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://alamakota/" ]
    }**
}

or B)

或B)

      "is_managed": false,
      "local_profile_id": 15191724,
      "name": "First user"
   },
   **"session": {
      "restore_on_startup_migrated": true,
   }**
}

I want to change it to look like this:

我想把它改成这样:

     "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" ]
   }
}

2 个解决方案

#1


1  

May be you want to parse it as json first and encode back to json if needed

可能是你想先将它解析为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); 

#2


0  

while(my $ln = <STDIN>){
    if ($ln =~ /^([ ]*)(\*\*)(.*)/) {
        print "$1"."$3";
    } elsif ($ln =~ /(.*)?(\*\*)([ ]*)$/) {
        print "$1"."$3";
    } else {
        print $ln;
    }
}

try running it as perl program.pl < input.txt

尝试将其作为perl program.pl 运行

#1


1  

May be you want to parse it as json first and encode back to json if needed

可能是你想先将它解析为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); 

#2


0  

while(my $ln = <STDIN>){
    if ($ln =~ /^([ ]*)(\*\*)(.*)/) {
        print "$1"."$3";
    } elsif ($ln =~ /(.*)?(\*\*)([ ]*)$/) {
        print "$1"."$3";
    } else {
        print $ln;
    }
}

try running it as perl program.pl < input.txt

尝试将其作为perl program.pl 运行