6

I use an old server without dos2unix and I would like to convert files containing Windows-style end-of-line (EOL) to Unix-style EOL. I am unfortunately not the admin so I can't install dos2unix. The tr method seems to be the only one that works.

cp script _p4 && tr -d '\r' < _p4 > script && rm _p4

Are there any easier methods to do this?

Edward
  • 2,509
cokedude
  • 1,121
  • dos2unix is a small and relatively self-contained binary. There's a sporting chance it will work on your server. If you have dos2unix installed on a machine with the same arch and OS (is this Linux?) then try copying it to your home directory and do ./dos2unix file_you_want_to_convert. Or, of course you could just download a suitable binary to the server directly. – Faheem Mitha Apr 28 '16 at 22:30

3 Answers3

14

If you have GNU sed you can do this:

sed -i 's/\x0D$//' script

Where "x0D" is the ASCII code for \r.

gapz
  • 331
  • 3
    \r is supported by sed, too. Why use harder-to-remember number when you can use simpler notation? – Alexander Batischev Apr 28 '16 at 22:17
  • I used to think that \r was not supported by all sed version, especially the GNU one. Things have changed, but I still use something which can be more portable to all sed version (maybe I'm wrong). – gapz Apr 28 '16 at 22:22
  • @gapz any idea why this one won't work sed -e '%s/^M//g' cookies sed: -e expression #1, char 1: unknown command:%' ` ? Is my sed to old? – cokedude Apr 28 '16 at 22:30
  • What are you trying to do with "%" ? Your are not in vim ;-). – gapz Apr 28 '16 at 22:36
  • Saw that on another page http://unix.stackexchange.com/questions/411/how-to-remove-ctrl-m-from-files-where-dos2unix-perl-tr-and-sed-are-not-presen. Couldn't get it to work so I asked my question here. – cokedude Apr 28 '16 at 23:05
  • "%" means "the whole text" in vim. If you want to do this with sed, just type "s/^M//g" (to get ^M if you to type CTRL+V then CTRL+M). – gapz Apr 28 '16 at 23:08
  • I wasn't able to get the \x0D to work with busybox sed. However \r did work with busybox sed. – Joshua Mar 13 '19 at 19:11
  • The busybox sed version I have is
    This is not GNU sed version 4.0```
    
    – Joshua Mar 13 '19 at 19:18
5

You can always write a script:

#!/bin/sh
for name in "$@"
do
    cp "$name" "$name"~ && tr -d '\r' < "$name"~ > "$name" && rm "$name"~
done

and name that dos2unix. No compiler is needed.

Thomas Dickey
  • 76,765
4

This command can be used to convert EOL characters without having dos2unix installed:

sed -i 's/.$//' script
JayJay
  • 160
  • 1
    Note that if you run this on a Linux-style EOL file, this answer will effectively destroy it (the sed command simply strips off all last characters). This behaviour is different from the dos2unix tool which ignores files that don't contain Windows-style line endings. – Edward Nov 04 '22 at 11:46