Python dos2unix one liner

Peter Otten __peter__ at web.de
Sat Feb 27 12:05:01 CET 2010


@ Rocteur CC wrote:

> But then I found
> http://wiki.python.org/moin/Powerful%20Python%20One-Liners
>   and tried this:
> 
> cat file.dos | python -c "import sys,re;
> [sys.stdout.write(re.compile('\r\n').sub('\n', line)) for line in
> sys.stdin]" >file.unix
> 
> And it works..

- Don't build list comprehensions just to throw them away, use a for-loop 
instead.

- You can often use string methods instead of regular expressions. In this 
case line.replace("\r\n", "\n").

> But it is long and just like sed does not do it in place.
> 
> Is there a better way in Python or is this kind of thing best done in
> Perl ?

open(..., "U") ("universal" mode) converts arbitrary line endings to just 
"\n"

$ cat -e file.dos
alpha^M$
beta^M$
gamma^M$

$ python -c'open("file.unix", "wb").writelines(open("file.dos", "U"))'

$ cat -e file.unix
alpha$
beta$
gamma$

But still, if you want very short (and often cryptic) code Perl is hard to 
beat. I'd say that Python doesn't even try.

Peter



More information about the Python-list mailing list