mantra2006 has asked for the wisdom of the Perl Monks concerning the following question:

Hi
I have a .txt file in unix which has pipe delimited values
abcd |abcd|abcd |abcd| abcd|
is it possible to get rid off space in between values and give as
abcd|abcd|abcd|abcd|abcd|
if I can get a single line command it would be great as the file is coming in
production it takes some time to move a perl script to production server
thanks in advance
Thanks & Regards
Sridhar

Replies are listed 'Best First'.
Re: Extracting data from a pipe delimited text file
by jettero (Monsignor) on Mar 29, 2007 at 18:48 UTC

    There are dozens of ways I imagine. I'd probably choose a lookahead: $line =~ s/\s+(?=\|)//g. Hrm, I just noticed there's space after one of them. A look-ahead is probably the wrong choice then. I'd probably choose $line =~ s/\s*\|\s*/\|/g instead — there may be a more efficient way though.

    I won't guarantee it's use in a production environment though. I've never tested the above.

    -Paul

      And in that vein, the following command should scan through a file and perform the operation on every line, leaving a backup with .bak appended. If this is Windows, change the single quotes to double quotes.

      perl -pi.bak -e 's/\s*\|\s*/\|/g' filename
Re: Extracting data from a pipe delimited text file
by roboticus (Chancellor) on Mar 30, 2007 at 03:06 UTC
    mantra2006:

    You might try something like this:

    #!/usr/bin/perl -w use strict; use warnings; my $in = <DATA>; my @fields = # Remove leading & trailing space from each list element map { s/^\s+//; s/\s+$//; $_ } # Split input string into fields at '|' split /\|/, $in; print join('|',@fields), "\n"; __DATA__ abcd |abcd|abcd | abcd | abcd|
    ...roboticus