【问题标题】:How to remove last character of Nth line linux如何删除第N行linux的最后一个字符
【发布时间】:2015-12-09 21:44:59
【问题描述】:

我有一个类似结构的大文档:

Data800,
Data900,
Data1000,
]
}

我将如何删除第三行到最后一行的最后一个字符(在这种情况下,逗号位于 Data1000 旁边)。输出应如下所示:

Data800,
Data900,
Data1000
]
}

它总是需要删除最后一个字符的倒数第三行。后端是linux,可以使用perl、bash、python等。

【问题讨论】:

    标签: python linux bash perl


    【解决方案1】:

    使用wc 计算行数和sed 进行编辑的简单解决方案:

    sed "$(( $(wc -l <file) - 2))s/,$//" file
    

    这会将编辑后的文件输出到标准输出;您可以使用sed -i 就地编辑。

    【讨论】:

    • 它就像一个冠军@rici。谢谢你这么及时的回复!
    【解决方案2】:

    Perl 的Tie::File 模块使这变得微不足道。它具有将数组绑定到磁盘文件的效果,因此对数组所做的任何更改都会反映在文件中

    看起来像这样(未经测试,因为我是从平板电脑发帖的)。输入文件的路径应作为命令行上的参数。行终止符已从数组中出现的字符串中删除,因此调用 chop 将删除文本的最后一个字符

    use strict;
    use warnings;
    
    use Tie::File;
    
    tie my @file, 'Tie::File', shift or die $!;
    
    chop $line[-3];
    
    untie @file;
    

    【讨论】:

    • 应该砍$file[-3];
    【解决方案3】:
    with open('a.txt', "a+") as f:
        f.seek(-2, 2)                 # Jump to the second last byte.
        counter = 0
        while counter < 2:            # if found EOLS still not enough  
            if f.read(1) == "\n":     # Count EOLs
                counter += 1
            f.seek(-2, 1)             # jump back the read byte plus one more
        position = f.tell()           # save position
        last_three_lines = f.read()   # read last three lines
        f.seek(position, 0)           # jump back 
        f.truncate()                  # remove all the rest
        f.write(last_three_lines[1:]) # write back necessary stuff
    

    输入:

    AAAAAa
    BBBBBb
    CCCCCc
    DDDDDd
    EEEEEe
    FFFFFf
    GGGGGg
    

    输出:

    AAAAAa
    BBBBBb
    CCCCCc
    DDDDDd
    EEEEE
    FFFFFf
    GGGGGg
    

    【讨论】:

      【解决方案4】:

      以下删除逗号,后跟]}(两者之间有可选的空格):

      perl -0777pe's/,(?=\s*[\]}])//g'
      

      用法:

      perl -0777pe's/,(?=\s*[\]}])//g' file.in >file.out   # Read from file
      perl -0777pe's/,(?=\s*[\]}])//g' <file.in >file.out  # Read from STDIN
      perl -i~ -0777pe's/,(?=\s*[\]}])//g' file            # In-place, with backup
      perl -i -0777pe's/,(?=\s*[\]}])//g' file             # In-place, without backup
      

      【讨论】:

      • 为什么投反对票?这实际上比公认的解决方案更好,因为它不仅适用于文件末尾,还适用于其他需要修复的地方。
      【解决方案5】:

      在 python 2.* 中:

      with open('/path/of/file', 'w+') as f:
          f.write(f.read().replace(',\n]', '\n]'))
      

      【讨论】:

        猜你喜欢
        • 2019-03-20
        • 1970-01-01
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        • 2022-01-17
        • 2014-07-13
        • 1970-01-01
        相关资源
        最近更新 更多