在csv文件中的字段上有条件地附加字符串

时间:2019-07-26 20:09:46

标签: linux bash csv awk

我正在尝试使用bash脚本转换如下的csv文件。标头和结构始终相同。

csv源文件:

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

条件值:

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

现在,我试图在没有第一行的情况下获得以下结果,并且如果每个标头都匹配这些条件值,则值现在用空格分隔:

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

我知道可以用awk完成此操作,但是我的awk知识有限。我尝试使用以下内容替换第一行,但仍然不知道如何扩展

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

3 个答案:

答案 0 :(得分:1)

好吧,您并没有错过这么多:)

awk -F',' 'NR>1{printf "Real_name=%s Real_title=%s Real_department=%s Real_score=%s\n",$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

答案 1 :(得分:0)

有了Miller(https://github.com/johnkerl/miller),它非常干净而且容易

mlr --icsv --ofs " " rename -r '(.*),Real_\1' input.txt

拥有

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

答案 2 :(得分:0)

$ cat tst.awk
BEGIN { FS="," }
NR==1 {
    for (i=1; i<=NF; i++) {
        h[i] = $i
    }
    next
}
{
    for (i=1; i<=NF; i++) {
        printf "Real_%s=%s%s", h[i], $i, (i<NF ? OFS : ORS)
    }
}

$ awk -f tst.awk 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