Using awk or sed to create new rows based on extraneous columns

I have a file that looks like this (columns are separated by tabs):

Owner    Phone    Car
Dan    111-111-1111    Avalon    Camry
Stacy    222-222-2222    Corolla    Yaris    Camry
Henry    333-333-3333    Prius

I want all additional cars to be on their own line below the original (with the owner and phone information copied for each additional car) so that it looks like this:

Owner    Phone    Car
Dan    111-111-1111    Avalon
Dan    111-111-1111    Camry
Stacy    222-222-2222    Corolla        
Stacy    222-222-2222    Yaris
Stacy    222-222-2222    Camry
Henry    333-333-3333    Prius

I was wondering if there is a way to implement this using awk or sed (preferably one liner).

+4
source share
3 answers

With the help of awkyou can scroll fields from 3end to end and print them together with the field 1and 2:

awk '{for(i=3;i<=NF;i++){print $1,$2,$i}}' file

Btw, , , column:

awk '{for(i=3;i<=NF;i++){print $1,$2,$i}}' file | column -t
+8

sed: tabe , , .

sed -n -e 's/\t/\n/g' -e 's/\n/\t/' -e 's/\n/\t/' -eP -e:l -e 's/\n/\t/' -eta -eb -e:a -e 's/\([^\t]*\t[^\t]*\)\t[^\t]*\(\t[^\t]*\)$/\1\2/' -etb -eb -e:b -eP -ebl < file

awk :)

+1

(GNU sed):

sed -r 's/\S+/\\S+/g;s/\s+/\\s+/g;s|^(.*)\\S\+|s/(\1)\\S+/\&\\n\\1/;\\//P;D|;q' file |
sed -rf - file

sed script () script , , script:

sed -r 's/^(\S+\s+\S+\s+)\S+/&\n\1/;//P;D' file

script ( ) . , , , , , .

+1

Source: https://habr.com/ru/post/1624367/


All Articles