使用sed或awk在第6个逗号后添加了一个字符

时间:2015-06-16 21:34:34

标签: bash awk sed

我有一个如下的csv文件:

last,first,A00XXXXXX,1888-01-01,2015-05-13,Elementary Algebra 34,
last,first,A00XXXXXX,1888-01-01,2015-05-13,Reading Comprehension 97,Sentence Skills 104,College Level Math 76,Elementary Algebra 115,

如果该行中不存在“阅读理解”这一短语,请在第5个逗号后添加逗号

我试图用AWK来解决这个问题,但似乎无法弄明白。我假设我需要使用gsub循环,但我无法弄清楚如何在$ 5之后添加','

最终目标如下:

last,first,A00XXXXXX,1888-01-01,2015-05-13,,Elementary Algebra 34,
last,first,A00XXXXXX,1888-01-01,2015-05-13,Reading Comprehension 97,Sentence Skills 104,College Level Math 76,Elementary Algebra 115,

1 个答案:

答案 0 :(得分:5)

使用sed

sed '/Reading Comprehension/! s/,/,,/5'

使用awk

awk -F, -v OFS=, '!/Reading Comprehension/ { $5 = $5 "," } 1'

输出:

last,first,A00XXXXXX,1888-01-01,2015-05-13,,Elementary Algebra 34,
last,first,A00XXXXXX,1888-01-01,2015-05-13,Reading Comprehension 97,Sentence Skills 104,College Level Math 76,Elementary Algebra 115,