Ale*_* S. 10 scripting perl sed file
我想知道我可以在sed中使用哪种模式来更改巨大文件的第一行(~2 GB).对sed的偏好只是因为我认为它必须比Python或Perl脚本更快.
这些文件具有以下结构:
field 1, field 2, ... field n
data
Run Code Online (Sandbox Code Playgroud)
并且,考虑到每个字段的标识符中都有空格的可能性,我需要用这种方式用下划线替换每个空格:
**BEFORE**
the first name,the second name,the first surname,a nickname, ...
data
**AFTER**
the_first_name,the_second_name,the_first_surname,a_nickname, ...
data
Run Code Online (Sandbox Code Playgroud)
任何指向正确模式的指针,或其他脚本解决方案都会很棒.
Leo*_*ans 22
编辑前10行
sed -i -e '1,10s/ /_/g'
Run Code Online (Sandbox Code Playgroud)
在Perl中,您可以在标量上下文中使用触发器运算符:
perl -i -pe 's/ /_/g if 1 .. 10'
Run Code Online (Sandbox Code Playgroud)
Ren*_*uis 10
我认为您不想使用任何需要将数据写入新文件的解决方案.
如果您非常确定所需要的是在大文本文件的第一行中将空格更改为下划线,则只需读取第一行,交换字符并将其写回原位:
#!/usr/bin/env perl
use strict;
my $filename = shift;
open (FH, "+< $filename") || die "can't open $filename: $!";
my $line = <FH>;
$line =~ s/ /_/g;
seek FH, 0, 0; # go back to the start of the file
printf FH $line;
close FH;
Run Code Online (Sandbox Code Playgroud)
要使用它,只需传递文件的完整路径即可更新:
# fixheader "/path/to/myfile.txt"
Run Code Online (Sandbox Code Playgroud)
您不太可能注意到Perl,Python和sed之间存在任何速度差异.您的脚本将花费大部分时间等待IO.
如果行长度相同,则可以就地编辑,否则必须创建新文件.
在Perl中:
#!/usr/bin/env perl
use strict;
my $filename = shift;
open my $in_fh, '<', $filename
or die "Cannot open $filename for reading: $!";
my $first_line = <$in_fh>;
open my $out_fh, '>', "$filename.tmp"
or die "Cannot open $filename.tmp for writing: $!";
$first_line =~ s/some translation/goes here/;
print {$out_fh} $first_line;
print {$out_fh} $_ while <$in_fh>; # sysread/syswrite is probably better
close $in_fh;
close $out_fh;
# overwrite original with modified copy
rename "$filename.tmp", $filename
or warn "Failed to move $filename.tmp to $filename: $!";
Run Code Online (Sandbox Code Playgroud)