Is there a Bash command to convert \r\n to \n?
Solution 1
There is:
dos2unix
Solution 2
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
.
Solution 3
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.
Solution 4
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\)")
Solution 5
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 POSIXPOSIX Awk does support
\r
and\15
, however the-i inplace
option is not POSIXd2u 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
Related videos on Youtube
David Powell
Updated on September 17, 2022Comments
-
David Powell over 1 year
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.
-
Bob_Gneu almost 14 years
dos2unix
is usually available, otherwisesed -e 's/\r$//'
-
Dennis Williamson almost 14 yearsNo, there's no Bash command for that, but there's
dos2unix
which is a Unix/Linux program to do what you want. -
vtest almost 14 yearsWhy don't you just use a sane text editor that lets you choose newline style when saving files?
-
-
ivan_pozdeev almost 11 yearsHas a side-effect of removing any other
\r
's too. They're highly uncommon though. -
Jared almost 10 yearsThis is the historically correct answer, though dos2unix is not always available these days.
-
dwana over 8 yearsI diden't even know ed,but it does the job (old but gold)
-
FK- over 4 yearsThis command worked for me when commands from other answers did not exist on the shared hosting I am using. Thanks :)
-
Ravindra Bawane over 3 yearsSome explanation and formatting would make this an answer. Right now it's just a comment.