I have the below lines in my file

# Employee Id  : ABC123,
# Employee Name: Vivek
# Employee Type: Temp                     Join Date: 31-jan-2014  Buz Code: 2098
# Employee Comments: 
#              Replacement for Jane
#   Country: India
#   State: Delhi
# Employee Id  : GGG67,
# Employee Name: Kumar
# Employee Type: Temp                     Join Date:15-jan-2014  Buz Code: 2176
# Employee Comments: 
#   Country: India
#   State: Delhi
#   Street: Kanot

From this, I need Employee ID, Employee Name and Buz Code in a table format for all employees. I tried with awk, but no results as expected.

Any suggestion?


It would seem less like a homework assignment if you showed what you've already tried. That said, here's a start - you need to grab the fields by matching on the field names, but not output them until you hit the next record. It would be convenient if there's a "#" between all records as you show...

$ awk -F: -f t.awk t
 ABC123,  Vivek
 GGG67,  Kumar

It's helpful with longer awk scripts to store them in a separate file

$ cat t.awk
/Employee Id/ {empid=$2}
/Employee Name/ {name=$2}
/#/ {print empid, name} # What happens if the next record is missing name?
END {print empid, name}

Or as a one-liner:

$ awk -F: '/Employee Id/ {empid=$2}; /Employee Name/ {name=$2}; /#/ {print empid, name}; END {print empid, name}' t
  • Hi Ian, Thanks for the one liner. I tried cat sample.txt | sed -n '/## EMPLOYEE DETAILS/,$p' | awk -F"" '/^# Employee Name:/{print $4;next}{print $10}' – Vivek Kumar.K Dec 9 '14 at 6:28
  • You're welcome. I see the question has been edited to use a different format (there is a # sign at the front of every line). Is that the actual format? Does this concept make sense now - grab the piece you need from each line, and don't output until the next record? – Ian McGowan Dec 9 '14 at 14:27
$ awk '{printf /Employee Id|Employee Name|Buz Code/? $NF" " : " "}' file

Prints last field $NF if found any pattern that matched like Employee Id or| ... else? print single space" ".

Result in column order:

ABC123, Vivek 2098      GGG67, Kumar 2176


awk '/Employee Id|Employee Name|Buz Code/ {if(++i%4==0) printf RS;printf $NF FS }' file

Note that RS means newline\n and FS means single space(by default).

Result in row order:

ABC123, Vivek 2098
GGG67, Kumar 2176
  • You are welcome. @VivekKumar.K please mark one of answer as accepted which is worked for your asked question. thank you and if you have new question please open it as new one. – αғsнιη Dec 10 '14 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.