Replacing specific characters in first column of text

前端 未结 2 334
心在旅途
心在旅途 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:14

    This might work for you:

    awk -F, -vOFS=, '{for(n=1;n<=3;n++)sub(/\./,"-",$1)}1' file
    abc-def-ghi-qqq.www,123.4561.789,ABC,DEF,GHI
    abc-def-ghq-qqq.www,124.4562.789,ABC,DEF,GHI
    abc-def-ghw-qqq.www,125.4563.789,ABC,DEF,GHI
    abc-def-ghe-qqq.www,126.4564.789,,,
    abc-def-ghr-qqq.www,127.4565.789,,,
    
    0 讨论(0)
  • 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.

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