24

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.

user25321
  • 381

9 Answers9

34

There is:

dos2unix
RaYell
  • 1,164
7

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.
6

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.

Zombo
  • 1
6

With sed and find that end with .txt, .php, .js, .css:

 sed -rie 's/\r\n/\n/' \
 $(find . -type f -iregex ".*\.\(txt\|php\|js\|css\)")
fitorec
  • 69
4

Doing this with POSIX is tricky:

  • POSIX Sed does not support \r or \15. Even if it did, the in place option -i is not POSIX

  • POSIX Awk does support \r and \15, however the -i inplace option is not POSIX

  • d2u and dos2unix are not POSIX utilities, but ex is

  • POSIX ex does not support \r, \15, \n or \12

To remove carriage returns:

awk 'BEGIN{RS="\1";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

awk 'BEGIN{RS="\1";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file
Zombo
  • 1
2

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'
0

Yes, use dos2unix. For example:

[justin@mybox ~]$ dos2unix myfile
0

$ recode dos.. FILE
$ flip -u FILE

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

0

cat input.csv | sed 's/\r/\n/g' > output.csv

Fahim
  • 101