Skip to content
Advertisement

Conditional append of strings on fields in a csv file

I am trying to convert a csv file like below with bash scripts. Headers and structures are always the same.

Source csv file:

name,title,department,score 
Jason,HR Manager,HR,10 
Alice,IT Director,Technology and Ops,8 
Jack,Network Team Lead,Technology and Ops,9

Conditional values (will change depending on the requirements)

Real_name=name
Real_title=title
Real_department=department
Real_score=score

Now I am trying to get the following result without the first row and values are now separated by spaces if each header matches those conditional values:

Real_name=Jason Real_title=HR Manager Real_department=HR Real_score=10
Real_name=Alice Real_title=IT Director Real_department=Technology and Ops Real_score=8
Real_name=Jack Real_title=Network Team Lead Real_department=Technology and Ops Real_score=9

I know this can be done with awk but my awk knowledge is limited. I tried the following to replace the first line but still don’t know how to expand on it

awk "{$1="test "$1;print}' my_sample_file

Updated: I can’t seem to make it work with input from a file with conditional values. Just thinking about a better and easy to maintain approach where those values will not necessarily be the same all the time. Could be MOD_title, MOD_name, etc. Instead of Real_title, Real_name, etc.

Advertisement

Answer

Well, you weren’t missing all that much 🙂

awk -F',' 'NR>1{printf "Real_name=%s Real_title=%s Real_department=%s Real_score=%sn",$1,$2,$3,$4}' my_sample_file 
Real_name=Jason Real_title=HR Manager Real_department=HR Real_score=10 
Real_name=Alice Real_title=IT Director Real_department=Technology and Ops Real_score=8 
Real_name=Jack Real_title=Network Team Lead Real_department=Technology and Ops Real_score=9
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement