Convert DOS line endings to Linux line endings in

2019-01-01 09:30发布

If I open files I created in Windows, the lines all end with ^M.
How do I delete these characters all at once?

26条回答
低头抚发
2楼-- · 2019-01-01 10:12
:%s/\r+//g

In Vim, that strips all carriage returns, and leaves only newlines.

查看更多
谁念西风独自凉
3楼-- · 2019-01-01 10:13

The comment about getting the ^M to appear is what worked for me. Merely typing "^M" in my vi got nothing (not found). The CTRL+V CTRL+M sequence did it perfectly though.

My working substitution command was

:%s/Ctrl-V Ctrl-M/\r/g

and it looked like this on my screen:

:%s/^M/\r/g
查看更多
琉璃瓶的回忆
4楼-- · 2019-01-01 10:14

Change the lineendings in the view:

:e ++ff=dos
:e ++ff=mac
:e ++ff=unix

This can also be used as saving operation (:w alone will not save using the lineendings you see on screen):

:w ++ff=dos
:w ++ff=mac
:w ++ff=unix

And you can use it from the command-line:

for file in $(ls *cpp)
do 
  vi +':w ++ff=unix' +':q' ${file}
done
查看更多
何处买醉
5楼-- · 2019-01-01 10:18

Usually there is a dos2unix command you can use for this, just make sure you read the manual as the GNU and BSD versions differ on how they deal with the arguments.

BSD version:

dos2unix $FILENAME $FILENAME_OUT
mv $FILENAME_OUT $FILENAME

GNU version:

dos2unix $FILENAME

Alternatively, you can create your own dos2unix with any of the proposed answers here, for example:

function dos2unix(){
    [ "${!}" ] && [ -f "{$1}" ] || return 1;

    { echo ':set ff=unix';
      echo ':wq';
    } | vim "${1}";
}
查看更多
像晚风撩人
6楼-- · 2019-01-01 10:21

To run directly into linux console: vim file.txt +"set ff=unix" +wq

查看更多
梦醉为红颜
7楼-- · 2019-01-01 10:21

dos2unix can directly modify the file contents.

You can directly use it on the file, with no need for temporary file redirection.

dos2unix input.txt input.txt

The above uses the assumed US keyboard. Use the -437 option to use the UK keyboard.

dos2unix -437 input.txt input.txt
查看更多
登录 后发表回答