Perl : split flat line's to $

Hi,

below is the software list of lines I have,

MozillaSrc 1.7.8.00.00 Mozilla 1.78 Source Distribution
NFS B.11.11 ONC/NFS; Network-File System,Information Services,Utilities
NParProvider B.11.11.01.04.01.01 nPartition Provider
NPartition A.01.02 Enhanced NPartition Commands
Networking B.11.11 HP-UX_Lanlink_Product
NisLdapServer B.04.00.02 The NIS/LDAP Gateway (ypldapd)

I would like to split this as follows.

"MozillaSrc" "1.7.8.00.00" "Mozilla 1.78 Source Distribution"

I'm unable to use substr - because the field's are of varying length. btw, the above lines are 'swlist' output from hpux box.

any help could be appreciated, thanks.

perl -e ' while (<>) { chomp; my @arr = split(/ /); print "\"$arr[0]\" \"$arr[1]\" \""; for ( my $i = 2; $i <= $#arr; $i++ ) { print " $arr[$i]" }; print " \"\n" } ' filename
#!/usr/bin/perl
while( <> )
{
        chomp;
        if ( / ([^\s]+) / ) {
                print "($`)($1)($')\n";
        }
}

print line should have been as,

 print "\"$`\" \"$1\" \"$'\"\n";

:slight_smile:

A sed version:

sed 's/ /|/2;s/\(.*\) \(.*\)|\(.*\)/"\1" "\2" "\3"/' input_file

thank you for all your inputs,

it did work, if the lines are as below (one space between FEATURE11-11<>B.11.11.0209.5<>Feature Enablement Patches for HP-UX 11i, Sept 2002)

but the actual line had some whitespace's in between (which were lost while pasting)

I have attached the line's as text file.

Purpose: 'swlist' gives software pkgs on a hp box, which has 3 fields as NAME, REVISION, INFO, I need to put as example -

$name = FEATURE11-11
$revision = B.11.11.0209.5
$info = Feature Enablement Patches for HP-UX 11i, Sept 2002

code for solaris works fine, as it has fixed string, hpux output is not fixed.

open(INFO, "pkginfo|") or die "an error occured: $!";
while (<INFO>) {
$CATEGORY = substr $, 0, 11;
$PKGINST = substr $
, 12, 32;
$NAME = substr $_, 45, 100;

<process a few things here..>
}

try this,

perl -e ' while (<>) { chomp; s/ */ /; my @arr = split(/  +/); print "\"$arr[0]\" \"$arr[1]\" \""; for ( my $i = 2; $i <= $#arr; $i++ ) { print " $arr[$i]" }; print " \"\n" } ' filename

Thanks Madhan, Anbu & shellLife, it was helpful.. finally i used the below to get it right...

open(INFO, "$file") or die "an error occured: $!";
while (<INFO>) {
chomp;
my @lines = split(' ', $_, 3);
$NAME = $lines[0];
$REVISION = $lines[1];
$INFO = $lines[2];

we can limit the number of sections the string's will be split into, by passing a third argument. For example, we're splitting our data into 3 fields, though we have many more than 3 occurrances of the delimiter.

got the output as>

NParCmds
A.01.02
Enhanced NPartition Commands