Perl program to replace tabs with spaces

2019-03-27 18:37发布

问题:

I'd like to write a Perl one-liner that replaces all 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?

回答1:

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);


回答2:

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).



回答3:

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

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


回答4:

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



回答5:

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


回答6:

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);