Python dos2unix one liner
__peter__ at web.de
Sat Feb 27 12:05:01 CET 2010
@ Rocteur CC wrote:
> But then I found
> 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
- 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
$ cat -e file.dos
$ python -c'open("file.unix", "wb").writelines(open("file.dos", "U"))'
$ cat -e file.unix
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.
More information about the Python-list