如何删除第n行linux的最后一个字符

2024-09-30 08:33:31 发布

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

我有一个结构相似的大文件:

Data800,
Data900,
Data1000,
]
}

如何删除第三行到最后一行的最后一个字符(在本例中,逗号位于Data1000旁边)。输出应如下所示:

^{pr2}$

它总是第3行到最后一行,其中需要删除最后一个字符。后端是linux,可以使用perl、bash、python等


Tags: 文件bashlinux字符结构perl逗号本例
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

输入:

^{pr2}$

输出:

AAAAAa
BBBBBb
CCCCCc
DDDDDd
EEEEE
FFFFFf
GGGGGg

一个简单的解决方案,使用wc来计算行数,sed来进行编辑:

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

它将在stdout上输出已编辑的文件;您可以使用sed -i就地编辑。在

Perl的^{}模块使得这一点变得微不足道。它的作用是将数组绑定到磁盘文件,这样对数组所做的任何更改都会反映在文件中

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

use strict;
use warnings;

use Tie::File;

tie my @file, 'Tie::File', shift or die $!;

chop $line[-3];

untie @file;

相关问题 更多 >

    热门问题