Is there a Bash command to convert \r\n to \n?

When I upload my scripts from Windows to Linux, I need a utility like this to make things work.

link|improve this question
5  
dos2unix is usually available, otherwise sed -e 's/\r$//' – roe Jun 24 '10 at 14:17
No, there's no Bash command for that, but there's dos2unix which is a Unix/Linux program to do what you want. – Dennis Williamson Jun 24 '10 at 14:27
1  
Why don't you just use a sane text editor that lets you choose newline style when saving files? – vtest Jun 25 '10 at 5:39
feedback

migrated from stackoverflow.com Jun 25 '10 at 1:32

This question came from our site for professional and enthusiast programmers.

7 Answers

There is:

dos2unix
link|improve this answer
feedback

There is a unix utility called conv that can convert line endings. It is often invoked with softlinks to u2d or d2u or unix2dos or dos2unix.

Additionally there are utilities called fromdos and todos.

link|improve this answer
feedback

Using man 1 ed (which edits files in-place without any previous backup - unlike: sed .. -i ".bak" ...):

ed -s file <<< $'H\ng/\r*$/s///\nwq'
link|improve this answer
feedback

Translate (tr) is available in all Unixes:

tr -d '\r'  # From \r\n line end (DOS/Windows), the \r will be removed so \n line end (Unix) remains.
link|improve this answer
feedback

Yes, use dos2unix. For example:

[justin@mybox ~]$ dos2unix myfile
link|improve this answer
feedback

You can use this to bulk replace all lines in multiple files that end with .html. You can change this to match a new name.

find -iname "*.html" -exec sh -cC '
sed 's/\r\n/\n/' "$1" > "$1"
' {} {} \;
link|improve this answer
8  
This isn't safe! First, the output redirection will generally zero the files before sed gets to read their contents (if your sed has it, use -i instead of shell redirection to solve this). Second, that sed command will remove the last character of each line, whether or not it's a \r -- run it on a non-DOS-format file, and it'll delete part of the contents of the files. – Gordon Davisson Jun 24 '10 at 16:22
feedback

$ recode dos.. FILE
$ flip -u FILE

(Each also exists for non-Ubuntu systems, but these links are handy.)

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.