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

2024-05-31 23:43:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要替换配置文件中的多行文本。 我可以使用sed(BusyBox v1.21.1)、perl(revision 5 version 14 subversion 2)或python(2.7)。你知道吗

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

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

或者 (二)

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

我想把它改成这样:

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

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

试着把它当作 perl program.pl < input.txt

可能您想首先将其解析为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); 

相关问题 更多 >