Marie Ducourau
Marie Ducourau

Reputation: 93

awk, print all columns and add new column with substr

I have this table

USI,Name,2D-3D
RO0001,Patate,2D
RO0002,Haricot,3D
RO0003,Banane,2D
RO0004,Pomme,2D
RO0005,Poire,2D

and I want this

USI,Name,2D-3D
RO0001,Patate,2D,RO_2D_Patate
RO0002,Haricot,3D,RO_3D_Haricot
RO0003,Banane,2D,RO_2D_Banane
RO0004,Pomme,2D,RO_2D_Pomme
RO0005,Poire,2D,RO_2D_Poire

I manage to obtain the construction "RO_2D_Patate" with awk

awk -F "," '{print substr($1,1,2)"_"substr($3,1,2)"_"$2}' Test4.txt

But I want to print all my column $0 before as my second table.

I tried everything But I am still a novice !!!!

Any idea over there?

Upvotes: 2

Views: 1555

Answers (3)

Claes Wikner
Claes Wikner

Reputation: 1517

awk -F, 'NR>1{print $0,substr($1,1,2)"_"$NF"_"$2}/USI/' OFS=, file

USI,Name,2D-3D
RO0001,Patate,2D,RO_2D_Patate
RO0002,Haricot,3D,RO_3D_Haricot
RO0003,Banane,2D,RO_2D_Banane
RO0004,Pomme,2D,RO_2D_Pomme
RO0005,Poire,2D,RO_2D_Poire

Upvotes: 0

CWLiu
CWLiu

Reputation: 4043

$ awk -F, -v OFS=, 'NR>1{$4=substr($1,1,2)"_"$3"_"$2}1' Test4.txt
USI,Name,2D-3D
RO0001,Patate,2D,RO_2D_Patate
RO0002,Haricot,3D,RO_3D_Haricot
RO0003,Banane,2D,RO_2D_Banane
RO0004,Pomme,2D,RO_2D_Pomme
RO0005,Poire,2D,RO_2D_Poire

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203577

awk -F, '{print $0 (NR>1 ? FS substr($1,1,2)"_"$3"_"$2 : "")}' Test4.txt

Upvotes: 2

Related Questions