Removing Windows newlines on Linux (sed vs. awk)

前端 未结 4 1637
我在风中等你
我在风中等你 2020-12-07 20:57

Have some delimited files with improperly placed newline characters in the middle of fields (not line ends), appearing as ^M in Vim. They originate from freebcp (on Centos 6

相关标签:
4条回答
  • 2020-12-07 21:36

    sed -e 's/\r//g' input_file

    This works for me. The difference of -e instead of -i command.

    Also I mentioned that see on different platforms behave differently. Mine is:sed --version This is not GNU sed version 4.0

    0 讨论(0)
  • 2020-12-07 21:40

    You can use the command line tool dos2unix

    dos2unix input
    

    Or use the tr command:

    tr -d '\r' <input >output
    

    Actually, you can do the file-format switching in vim:

    Method A:
    :e ++ff=dos
    :w ++ff=unix
    :e!
    
    Method B:
    :e ++ff=dos
    :set ff=unix
    :w
    

    EDIT

    If you want to delete the \r\n sequences in the file, try these commands in vim:

    :e ++ff=unix           " <-- make sure open with UNIX format
    :%s/\r\n//g            " <-- remove all \r\n
    :w                     " <-- save file
    

    Your awk solution works fine. Another two sed solutions:

    sed '1h;1!H;$!d;${g;s/\r\n//g}' input
    sed ':A;/\r$/{N;bA};s/\r\n//g' input
    
    0 讨论(0)
  • 2020-12-07 21:42

    I believe some versions of sed will not recognize \r as a character. However, you can use a bash feature to work around that limitation:

    echo $string | sed $'s/\r//'
    

    Here, you let bash replace '\r' with the actual carriage return character inside the $'...' construct before passing that to sed as its command. (Assuming you use bash; other shells should have a similar construct.)

    0 讨论(0)
  • 2020-12-07 21:48

    Another method

    awk 1 RS='\r\n' ORS=
    
    • set Record Separator to \r\n
    • set Output Record Separator to empty string
    • 1 is always true, and in the absence of an action block {print} is used
    0 讨论(0)
提交回复
热议问题