Replacing specific characters in first column of text

前端 未结 2 333
心在旅途
心在旅途 2021-01-13 04:36

I have a text file and I\'m trying to replace a specific character (.) in the first column to another character (-). Every field is delimited by comma. Some of the lines hav

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 05:29

    . is regexp notation for "any character". Escape it with \ and it means .:

    $ awk -F, '{gsub(/\./,"-",$1); print}' textfile.csv 
    abc-def-ghi 123.4561.789 ABC DEF GHI
    abc-def-ghq 124.4562.789 ABC DEF GHI
    abc-def-ghw 125.4563.789 ABC DEF GHI
    abc-def-ghe 126.4564.789   
    abc-def-ghr 127.4565.789   
    $ 
    

    The output field separator is a space, by default. Set OFS = "," to set that:

    $ awk  -F, 'BEGIN {OFS=","} {gsub(/\./,"-",$1); print}' textfile.csv 
    abc-def-ghi,123.4561.789,ABC,DEF,GHI
    abc-def-ghq,124.4562.789,ABC,DEF,GHI
    abc-def-ghw,125.4563.789,ABC,DEF,GHI
    abc-def-ghe,126.4564.789,,,
    abc-def-ghr,127.4565.789,,,
    

    This still allows changing multiple fields:

    $ awk  -F, 'BEGIN {OFS=","} {gsub(/\./,"-",$1); gsub("1", "#",$2); print}' textfile.csv 
    abc-def-ghi,#23.456#.789,ABC,DEF,GHI
    abc-def-ghq,#24.4562.789,ABC,DEF,GHI
    abc-def-ghw,#25.4563.789,ABC,DEF,GHI
    abc-def-ghe,#26.4564.789,,,
    abc-def-ghr,#27.4565.789,,,
    

    I don't know what -OFS, does, but it isn't a supported command line option; using it to set the output field separator was a mistake on my part. Setting OFS within the awk program works well.

提交回复
热议问题