netnewbie
netnewbie

Reputation:

Using Perl, how can I replace all whitespace in a file with newlines?

For example text file:

    Speak friend and enter

using a Perl script to remove whitespace and replace with carriage-return

    Speak
    friend 
    and
    enter

Upvotes: 2

Views: 21206

Answers (5)

Donato Azevedo
Donato Azevedo

Reputation: 1418

If you want inplace editing you can use the -i switch. Check out perlrun to see how it's done, but, basically:

perl -p -i.bak -e 's/\s+/\n/g'

Upvotes: 1

monkey_p
monkey_p

Reputation: 2879

You can use sed

sed -e "s/[ ]/\n/g"

or anything that works with regular expressions

"s/[ ]/\n/g"

Upvotes: 1

Sinan Ünür
Sinan Ünür

Reputation: 118118

#!/usr/bin/perl -l

use strict;
use warnings;

print join "\n", split while <>;

Upvotes: 1

arolson101
arolson101

Reputation: 1502

create a file test.pl:

open my $hfile, $ARGV[0] or die "Can't open $ARGV[0] for reading: $!";
while( my $line = <$hfile> )
{
    $line =~ s/\s+/\n/g;
    print $line;
}
close $hfile;

then run it like:

perl test.pl yourfile.txt

or, if you don't want to use a file, you can do it all from the command line like:

perl -p -e "s/\s+/\n/g" yourfile.txt

Upvotes: 3

Peter Kovacs
Peter Kovacs

Reputation: 2725

perl -p -e 's/\s+/\n/g'

Upvotes: 21

Related Questions