Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last occurrence of a character in a field with awk

Tags:

regex

bash

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)}

and then integrate it in

{var2=gensub(/ /,",",var1,$4); print var2}

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!

like image 534
Nilsic Avatar asked Sep 28 '22 16:09

Nilsic


2 Answers

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

Get the book Effective Awk Programming by Arnold Robbins.

Very well-written question btw!

like image 176
Ed Morton Avatar answered Oct 09 '22 01:10

Ed Morton


Here is a short awk

awk '{$NF=RS$NF;sub(" "RS,",")}1' file
John,Doe,Abc fgh,123,Abc
John,Doe,Ijk-nop,45D,Def
John,Doe,Qr s Uvw,6,Ghi

Updated due to Eds comment.

Or you can use the rev tools.

rev file | sed 's/ /,/' | rev
John,Doe,Abc fgh,123,Abc
John,Doe,Ijk-nop,45D,Def
John,Doe,Qr s Uvw,6,Ghi

Revers the line, then replace first space with ,, then revers again.

like image 2
Jotne Avatar answered Oct 09 '22 01:10

Jotne