开发者

Perl program to replace tabs with spaces

I'd like to write a Perl one-liner that replaces a开发者_开发问答ll tabs '\t' in a batch of text files in the current directory with spaces, with no effect on the visible spacing.

Can anyone show me how to do this?


This is in FAQ:

1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;

Or you can just use the Text::Tabs module (part of the standard Perl distribution).

use Text::Tabs;
@expanded_lines = expand(@lines_with_tabs);


You don't need a Perl one-liner for this, you could use expand instead:

The expand utility shall write files or the standard input to the standard output with characters replaced with one or more characters needed to pad to the next tab stop.

The expand utility will even take care of managing tab stops for you and that seems to be part of your "with no effect on the visible spacing" requirement, a Perl one-liner probably would't (but I bet someone here could provide a one-liner that would).


Use Text::Tabs. The following is adapted only very slightly from the documentation:

perl -MText::Tabs -n -i.orig -e 'print expand $_' *


perl -p -i -e 's/\t/ /g' file.txt would be one way to do this


$ perl -wp -i.backup -e 's/\t/    /g' *


You can use s/// to achieve this. Perhaps you have a line of text stored in $line:

$line =~ s/\t/    /g;

This should replace each tab (\t) with four spaces. It just depends on how many spaces one tab is in your file.

Here's something that should do it pretty quickly for you; edit it how you will.

open(FH, 'tabz.txt');

my @new;

foreach my $line (<FH>) {
    $line =~ s/\t/    /g; # Add your spaces here!
    push(@new, $line);
}

close(FH);

open(FH, '>new.txt');
printf(FH $_) foreach (@new);
close(FH);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜