Replace last occurrence of a character in a field with awk

前端 未结 2 1855
抹茶落季
抹茶落季 2021-01-13 23:13

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,D         


        
相关标签:
2条回答
  • 2021-01-13 23:37

    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!

    0 讨论(0)
  • 2021-01-13 23:56

    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.

    0 讨论(0)
提交回复
热议问题