Reputation: 45
I have a text file with the following structure. I want to remove first part before comma and keep rest and then match them to the 2nd column and put them in individual rows.
INPUT:
A,B,C London
G,L,K,I Berlin
Q,O,M,J Madrid
I want a output like this:
OUTPUT:
B London
C London
L Berlin
K Berlin
I Berlin
O Madrid
M Madrid
J Madrid
Upvotes: 0
Views: 111
Reputation: 126722
A Perl way
perl -aF[\\s,]+ -nE'say "$_ $F[-1]" for @F[1..$#F-1]' myfile
output
B London
C London
L Berlin
K Berlin
I Berlin
O Madrid
M Madrid
J Madrid
Upvotes: 3
Reputation: 7959
Since you have perl
tag:
perl -alne '$F[0]=~s/^.*?,//g; @a=split /,/,$F[0]; map { print "$_ $F[1]" } @a' file
B London
C London
L Berlin
K Berlin
I Berlin
O Madrid
M Madrid
J Madrid
Explanation:
-a
Splits fields into array @F
-l
prints \n
after every print statement-n
Loops trough file$F[0]=~s/^.*?,//g;
Removes anything between begging of string
and ,
for position 0 of array @F@a=split /,/,$F[0];
Creates array @a
map { print "$_ $F[1]" } @a
could also be written as foreach(@a){print "$_ $F[1]"}
Shorter version using shift
:
perl -alne '@a=split /,/,$F[0]; shift @a; print "$_ $F[1]" for @a' file
Upvotes: 2
Reputation: 289505
This can be a way with awk:
$ awk '{n=split($1, a, ","); for (i=2; i<=n; i++) print a[i], $NF}' file
B London
C London
L Berlin
K Berlin
I Berlin
O Madrid
M Madrid
J Madrid
n=split($1, a, ",")
slices the first field into pieces based on comma as delimiter. split
returns the number of slices and we store that.for (i=2; i<=n; i++) print a[i], $NF
we then loop through all these slices, starting from the 2nd one, printing each one together with the last field (city name).Upvotes: 0