输入数据:
id,location_id,name,title,[email protected],department
1,1,Susan houston,Director of Services,[email protected],
2,1,Christina Gonzalez,Director,[email protected],
3,2,Brenda brown,"Director, Second Career Services",[email protected],
4,3,Howard Lader,"Manager, Senior Counseling",[email protected],
8,6,Bart charlow,Executive Director,[email protected],
9,7,Bart Charlow,Executive Director,[email protected],
我需要在电子邮件部分后添加一个字符来复制电子邮件,即[email protected]将变为[email protected](电子邮件部分后的数字需要从第二列中取出)。我如何在 Bash 中对所有条目执行此操作?
假设当你说:
您只是指该电子邮件地址的第二次出现,而不是全部,然后使用任何 awk:
这个命令的核心是使用第二个字段的值( )
sub()
替换,然后使用其自身(替换为第一部分中匹配的内容)替换。@
$2
&
有关使用 awk 处理 CSV 的更多信息,请参阅whats-the-most-robust-way-to-efficiently-parse-csv-using-awk。
使用 Miller (
mlr
) 将数据读取为 CSV,计算字段每个值出现的次数[email protected]
(添加一个名为 的临时字段),如果需要则count
修改该字段(如果大于 1),然后删除临时字段。[email protected]
count
count
字段的修改
[email protected]
由测试触发,通过在字符上拆分字段,然后将各部分重新拼接在一起并插入字段的值来$count > 1
执行。@
location_id
除了执行拆分+连接操作外,您还可以通过
sub()
调用来执行此操作,类似于 Ed Morton 在他的awk
代码中所展示的内容:结果:
使用“仅
bash
”(无外部实用程序):这对这个答案开头的支持 CSV 的代码(使用 Miller)可以毫无问题地处理输入做出了一些假设:
[email protected]
该字段中没有值[email protected]
。@
字符在每个输入行上仅出现一次,并且位于[email protected]
字段中。输出: