开发者

Finding and deleting lines less than X chars long

I have a list of items in a file,

foobar
barfoo
bar
faaboo
foo
boofar
fo
b

Using perl, I'm just after script 开发者_运维问答that will go through the filename and delete all items 3 characters or less. Overwrite the existing filename (without creating a new, or temp filename), Thus the list will be become.

foobar
barfoo
faaboo
boofar


One-liner:

perl -ine '{print if /.{4}/}' filename

You can use length (add 1 for newline character) instead of regex if that's your fancy, as Jonathan Leffler noted in comments - it's probably faster on very large files. Here's a Windows version (note the use of double quotes required by cmd instead of single quotes):

perl.exe -i.bak -n -e "{print if length > 4}" filename

Also, to answer your comment, unfortunately you can not execute in-place -i edits on Windows without a backup file. Please refer to this SO post for detailed explanation (again, Windows limitation, not Perl's) as well as a workaround.


Tie::File

use warnings;
use strict;
use Tie::File;

my $file = shift;
tie my @array, 'Tie::File', $file or die;
@array = grep { length > 3 } @array;
untie @array;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜