Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl program to replace tabs with spaces

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?

like image 388
dvanaria Avatar asked May 13 '11 20:05

dvanaria


3 Answers

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);
like image 61
Eugene Yarmash Avatar answered Oct 02 '22 14:10

Eugene Yarmash


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

like image 37
mu is too short Avatar answered Oct 02 '22 12:10

mu is too short


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

perl -MText::Tabs -n -i.orig -e 'print expand $_' *
like image 33
Chris Johnsen Avatar answered Oct 02 '22 14:10

Chris Johnsen