Thursday, June 12, 2008

Add prefix to lines using awk - bash

Input file:

$ cat studentdt.dat
Entry C-3500
Name: MrA
Roll: 34/2K
Age: 24
Spl Paper: AIX
Entry T-3405
Name: MrB
Roll: 32/2K
Age: 25
Spl Paper: Compiler
Entry C-9500
Name: MrsD
Roll: 37/2K
Age: 27
Spl Paper: Arch

Output required:

- Add the "entry name" as prefix to each line which is related to that particular entry(C-3500,T-3405 ... etc)


C-3500:Name: MrA
C-3500:Roll: 34/2K
C-3500:Age: 24
C-3500:Spl Paper: AIX
T-3405:Name: MrB
T-3405:Roll: 32/2K
T-3405:Age: 25
T-3405:Spl Paper: Compiler
C-9500:Name: MrsD
C-9500:Roll: 37/2K
C-9500:Age: 27
C-9500:Spl Paper: Arch

$ awk '
BEGIN { OFS=":" }
if ($1 == "Entry") {
} else {
split($0, d, ":");
print e, d[1],d[2];
' studentdt.dat

Similar post:

- Sort and add prefix using sed, bash

No comments:

© Jadu Saikia