Comment convert DOS/Windows newline (CRLF) vers Unix newline (LF)

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Comment convert DOS/Windows newline (CRLF) vers Unix newline (LF)

Message par ForumBot »

How to convert DOS/Windows newline (CRLF) to Unix newline (LF)




Source : Stack Overflow [windows]

ayi
Site Admin
Messages : 13176
Inscription : mer. avr. 22, 2026 5:21 pm

Re: Comment convert DOS/Windows newline (CRLF) vers Unix newline (LF)

Message par ayi »

Vous pouvez utiliser tr to convert from DOS to Unix; cependant, vous pouvez only do this safely if CR appears in your file only as the first byte of a CRLF byte pair. This is usually the case. You then use:


tr -d '\015' <DOS-file >UNIX-file


Notez que the name DOS-file is different from the name UNIX-file; if you try to use the same name twice, you will end up with no data in the file.


Vous pouvez’t do it the other way round (with standard ‘tr’).


If you know how to enter carriage return into a script (control-V, control-M to enter control-M), then:


sed 's/^M$//'     # DOS to Unix
sed 's/$/^M/' # Unix to DOS


where the ‘^M’ is the control-M character. Vous pouvez également use the bash ANSI-C Quoting mechanism to specify the carriage return:


sed $'s/\r$//'     # DOS to Unix
sed $'s/$/\r/' # Unix to DOS


Cependant, if you’re going to have to do this very often (more than once, roughly speaking), it is far more sensible to install the conversion programs (e.g. dos2unix and unix2dos, or perhaps dtou and utod) and use them.


If vous devez process entire directories and subdirectories, vous pouvez utiliser zip:


zip -r -ll zipfile.zip somedir/
unzip zipfile.zip


This will create a zip archive with line endings changed from CRLF to CR. unzip will then put the converted files back in place (and ask you file by file - vous pouvez answer: Yes-to-all). Credits to @vmsnomad for pointing this out.

Répondre

Revenir à « Performance & Dépannage »