Ayesha
Ayesha

Reputation: 905

Regex to convert spaces into commas

I have a file with below data

Name        Id    Contact        Email
raj       3232    408333       [email protected]
anu      353453   409242       [email protected]

I want to replace the above file with below data.

Name,Id,Contact,Email
raj,3232,408333,[email protected]
anu,353453,409242,[email protected]

Replace all the spaces in a line with commas and ignore the spaces between each new line. How can I achieve this ??

I read online that $value =~ s/\s+/,/g; would convert all the spaces and tabs in a line and replace it with a comma. but it doesn't execute that way.

Can someone advise please??

Here is my exact code. It might confuse a bit. but here it is. The file gets copied in a array, then changes made to array as per needed. Once changes are made, the array is written back to the file.

open(FILE, $filename) || die "File not found";
my @lines = <FILE>;
close(FILE);

my @newlines;
foreach(@lines) {
            $_ =~ tr/ \t/,/s;       
            push(@newlines,$_);  
}


open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
print $fh @newlines;
close($fh);

}

Upvotes: 0

Views: 967

Answers (2)

Jeremy Jones
Jeremy Jones

Reputation: 5641

To do this on the terminal you can just do this:

perl -pe 'tr/ /,/s' datafile.txt

To replace the original file with the changed version, just add an i option:

perl -pi -e 'tr/ /,/s' datafile.txt

Output:

$ perl -pe 'tr/ /,/s' datafile.txt 
Name,Id,Contact,Email
raj,3232,408333,[email protected]
anu,353453,409242,[email protected]
$

.

$ perl -pi -e 'tr/ /,/s' datafile.txt 
$ more datafile.txt 
Name,Id,Contact,Email
raj,3232,408333,[email protected]
anu,353453,409242,[email protected]
$ 

Upvotes: 0

melpomene
melpomene

Reputation: 85827

You could do it without a regex:

$value =~ tr/ \t/,/s;

tr/// is documented in perldoc perlop (or perldoc -f tr if your perldoc is new enough).

Upvotes: 2

Related Questions