Reputation: 389
I have a file in following format
a 2 10 a,c
b 5 8 c
b 7 2 a
c 9 0 c,d,a
Now for those who have multiple entries in the last column, I want a new line (column 1-3 remaining same) for each of the entry in the last column in the following format
a 2 10 a
a 2 10 c
b 5 8 c
b 7 2 a
c 9 0 d
c 9 0 c
c 9 0 a
Some suggestion please.
Upvotes: 0
Views: 75
Reputation: 74685
Use spaces and commas as the field separator, then print the 1st,2nd,3rd and i
th field from the 4th field onward:
awk -F'[[:space:],]+' '{for(i=4;i<=NF;++i)print $1,$2,$3,$i}' file
Output:
a 2 10 a
a 2 10 c
b 5 8 c
b 7 2 a
c 9 0 c
c 9 0 d
c 9 0 a
If you're not adverse to a bit of Perl:
perl -F'[,\s]+' -lane 'print "@F[0..2,$_]" for 3..$#F' file
Again, split the line on commas and spaces. More or less the same logic as the awk one but a couple of characters shorter :)
Upvotes: 4
Reputation: 77155
Here is one way:
$ awk '{n=split($NF,ary,/,/); NF--; for(i=1;i<=n;i++) print $0, ary[i]}' file
a 2 10 a
a 2 10 c
b 5 8 c
b 7 2 a
c 9 0 c
c 9 0 d
c 9 0 a
We split the last field on ,
and store the fields in an array called ary
. The split
returns the number of fields splitted which we store in a variable n
. We remove the last field from the line using NF--
and iterate through the number of elements (from the last field) and print the line along with the element from our ary
.
Upvotes: 3