代码之家  ›  专栏  ›  技术社区  ›  Alexander Morland

删除特定换行符的Cli命令

  •  1
  • Alexander Morland  · 技术社区  · 9 年前

    ```
    json :
    {
      "something": "here"
    }
    ```
    

    我想解决所有这些问题,使其成为有效的降价,即:

    ```json
    {
      "something": "here"
    }
    ```
    

    如何跨任意数量的文件有效地做到这一点?

    我在谷歌上搜索了一下,发现了类似的问题,但无法将它们的解决方案转换为我的特定需求。似乎SED在多行匹配方面并不擅长,而且包含`字符显然也会引起问题。

    我试过了

    perl -pe "s/\njson :/json/g"
    

    但这并没有给出任何匹配。

    1 回复  |  直到 9 年前
        1
  •  4
  •   Borodin    9 年前

    要使Perl程序工作,需要更改 input record separator $/ . 一个简单的 BEGIN undef 在程序运行其 while 环

    $ perl -pe 'BEGIN{undef $/} s/\njson :/json/g' foo
    ```json
    {
      "something": "here"
    }
    

    现在,Perl将同时在整个文件中发出咕噜声,这对于降价文档来说应该很好。如果您想处理大小为几GB的文件,请使用更多RAM。

    请注意,您需要 -i 也可以进行就地编辑。

    $ perl -pi -e '...' *
    

    更简短的版本是使用 -0 标志而不是 块来告诉Perl关于输入记录分隔符的信息。 perlrun 这样说:

    模式任何大于等于0400的值都会导致Perl将文件整个吞掉, 但按照惯例,0777是通常用于此的值 意图


    您可以通过使用 re 'debug' pragma ,打开正则表达式的调试模式。它会告诉你的。

    $ perl -Mre=debug -pe 's/\njson :/json/g' foo
    Compiling REx "\njson :"
    Final program:
       1: EXACT <\njson :> (4)
       4: END (0)
    anchored "%njson :" at 0 (checking anchored isall) minlen 7 
    Matching REx "\njson :" against "```%n"
    Regex match can't succeed, so not even tried
    ```
    Matching REx "\njson :" against "json :%n"
    Intuit: trying to determine minimum start position...
      Did not find anchored substr "%njson :"...
    Match rejected by optimizer
    json :
    Matching REx "\njson :" against "{%n"
    Regex match can't succeed, so not even tried
    {
    Matching REx "\njson :" against "  %"something%": %"here%"%n"
    Intuit: trying to determine minimum start position...
      Did not find anchored substr "%njson :"...
    Match rejected by optimizer
      "something": "here"
    Matching REx "\njson :" against "}%n"
    Regex match can't succeed, so not even tried
    }
    Matching REx "\njson :" against "```%n"
    Regex match can't succeed, so not even tried
    ```
    Matching REx "\njson :" against "%n"
    Regex match can't succeed, so not even tried
    
    Freeing REx: "\njson :"
    

    赠品是:

    Matching REx "\njson :" against "```%n"
    Regex match can't succeed, so not even tried
    
    推荐文章