【问题标题】:Replace multiline text in file using regex on Linux在 Linux 上使用正则表达式替换文件中的多行文本
【发布时间】:2015-07-27 10:10:46
【问题描述】:

我需要替换配置文件中的多行文本。 我可以使用 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/" ]
    }**
}

或 B)

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

【问题讨论】:

  • 您想要的更改也是如此:从“会话”部分中删除*,并将主机名转换为IP?该列表中可能有很多主机名吗?在没有 urls_to_restore_on_startup 条目的 B) 示例中,您希望发生什么?
  • 这看起来像 JSON。是 JSON 吗?如果是 JSON,你不想用正则表达式来做这个。

标签: python regex perl sed


【解决方案1】:

您可能想先将其解析为 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】:
    while(my $ln = <STDIN>){
        if ($ln =~ /^([ ]*)(\*\*)(.*)/) {
            print "$1"."$3";
        } elsif ($ln =~ /(.*)?(\*\*)([ ]*)$/) {
            print "$1"."$3";
        } else {
            print $ln;
        }
    }
    

    尝试运行它 perl program.pl &lt; input.txt

    【讨论】:

    • 这只是为了删除**,我不确定你到底想要什么。但这只会对 ** 有所帮助,正如其他 cmets 中提到的那样,如果它的 JSON 和更多逻辑将主机名解析为 IP,则必须使用 JSON 解析器
    猜你喜欢
    • 2020-04-03
    • 2018-04-23
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2017-10-18
    相关资源
    最近更新 更多