问题描述
我正在尝试用awk替换字段中最后一次出现的字符.给出的是这样的文件:
I'm trying to replace the last occurrence of a character in a field with awk. Given is a file like this one:
John,Doe,Abc fgh 123,Abc
John,Doe,Ijk-nop 45D,Def
John,Doe,Qr s Uvw 6,Ghi
我想用逗号,"替换最后一个空格",基本上将字段分为两部分.结果应该看起来像这样:
I want to replace the last space " " with a comma ",", basically splitting the field into two. The result is supposed to look like this:
John,Doe,Abc fgh,123,Abc
John,Doe,Ijk-nop,45D,Def
John,Doe,Qr s Uvw,6,Ghi
我尝试创建一个变量,其中包含字段中出现空格的次数
I've tried to create a variable with the number of occurrences of spaces in the field with
{var1=gsub(/ /,"",$3)}
然后将其集成到
{var2=gensub(/ /,",",var1,$4); print var2}
但是gensub的how-argument不允许数字和G/g之外的任何字符.
but the how-argument in gensub does not allow any characters besides numbers and G/g.
我在此处找到了类似的线程,但是无法使解决方案适应我的问题.
I've found a similar thread here but wasn't able to adapt the solution to my problem.
我对此还很陌生,所以我们将不胜感激!
I'm fairly new to this so any help would be appreciated!
推荐答案
对于gensub(),使用GNU awk:
With GNU awk for gensub():
$ awk 'BEGIN{FS=OFS=","} {$3=gensub(/(.*) /,"\\1,","",$3)}1' file
John,Doe,Abc fgh,123,Abc
John,Doe,Ijk-nop,45D,Def
John,Doe,Qr s Uvw,6,Ghi
获得阿诺德·罗宾斯(Arnold Robbins)的《有效的Awk编程》一书.
Get the book Effective Awk Programming by Arnold Robbins.
写得很好的问题!
这篇关于用awk替换字段中最后一次出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!