Remove all white space in a file and replace them with a comma using Vim

前端 未结 4 1934
栀梦
栀梦 2021-01-31 10:12

Anyone has an idea how to remove all white space and replace them with a comma , in a file using Vim ? File input example (words could be everywhere !):

相关标签:
4条回答
  • 2021-01-31 10:25

    when converting a text file with headers and text fields with spaces I used %s/\s\{2,}/,/g

    0 讨论(0)
  • 2021-01-31 10:26

    If the file contains n number of line and contains spaces at the start of each line, end of each line and in between. And you want to remove spaces at start and end and replace in between multiple spaces with a comma ",". And also redirect the output and save to a new file keeping the original file as it is.

    Use the following command -

    sed -e 's/^[ \t]*// ; s/[[:blank:]]*$// ; s/\s\+/,/g ; s/,$//' input-file-name | tee output-file-name
    

    give paths of the input file name if not in the same directory.

    or you can write all these -

    "s/^[ \t]*//
    s/[[:blank:]]*$//
    s/\s\+/,/g ; s/,$//"
    

    in a txt file save it. and use -f option.

    so the command becomes -

    sed -f commands.txt input-file-name.txt | tee output-file-name.txt
    

    commnads.txt contains the above conditions of sed command

    0 讨论(0)
  • 2021-01-31 10:31

    First delete the blank lines:

    :g/^\s*$/d
    

    Then use a substitution (:s///) over each line (%) to replace all (g) continuous whitespace (\s\+) with a comma (,).

     :%s/\s\+/,/g
    
    0 讨论(0)
  • 2021-01-31 10:37

    Another way to do it :

    %s/\s\{1,}/,/gc

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