I have this form of line:
xxx| aaa yyy| bbb ccc zzz| ddd eee
I want to split and distribute in this array with perl:
xxx| aaa
yyy| bbb
yyy| ccc
zzz| ddd
zzz| eee
Ok, transferred from comments. I put it there while the question was closed.
With a substitution regex, we iterate through the string, extracting a key and the values. The value string is split on whitespace, and stored in an anonymous array in %hash
, with the corresponding key.
Code:
use strict;
use warnings;
use v5.10; # to enable say
$_="xxx| aaa yyy| bbb ccc zzz| ddd eee";
my %hash;
while (s/(\w+)\|([ \w]+\b(?!\|))//) {
$hash{$1} = [ split ' ',$2 ];
}
for my $key (keys %hash) {
for my $val (@{$hash{$key}}) {
say "$key | $val";
}
}
Output:
xxx | aaa
yyy | bbb
yyy | ccc
zzz | ddd
zzz | eee
One-liner solution:
perl -lne'for(split/ (?=\w+\|)/){($p,@a)=split/ /;print"$p $_"for@a}'
usage:
$ echo "xxx| aaa yyy| bbb ccc zzz| ddd eee" | perl -lne'for(split/ (?=\w+\|)/){($p,@a)=split/ /;print"$p $_"for@a}'
xxx| aaa
yyy| bbb
yyy| ccc
zzz| ddd
zzz| eee
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.