Swap contents of two files

zsh, 20

<i*>t;<o*>i*;mv t o*

Python, 77

import os;t='.txt';r,i,o,x=[os.rename,'i'+t,'o'+t,'1'+t];r(i,x);r(o,i);r(x,o)

Python, 65

import os;t='.txt'
for a,b in zip('iox','xio'):os.rename(a+t,b+t)

Python, 63

import os;t='.txt'
for a,b in 'ix','oi','xo':os.rename(a+t,b+t)

PHP, 68

<?$r=rename;$t='.txt';$r("i$t","x");$r("o$t","i$t");$r("x","o$t");?>

Windows Batch File, 42

move i.txt x&move o.txt i.txt&move x o.txt

Windows Batch File (args), 30

move %1 x&move %2 %1&move x %2

Two bash based ansers; 52 and 62 chars

shell: diff + patch (+ tee + sed...) 52

Maybe not the shorter, but I find this fun (and there is no use of temporary file):

diff -u [io]*|tee >(patch -r -)|sed 1s/i/o/|patch -R

Where content is swapped and files are modified in place:

Sample run

swapContent() { diff -u $1 $2|tee >(patch -r -)|sed 1s/$1/$2/|patch -R ;}

while read page file ;do man -Pcol\ -b $page >$file.txt;done <<<$'man i\nbash o'
printf "%s %8d  %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))
swapContent [io]*
printf "%s %8d  %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))

Could produce something like:

i.txt    46007  1da1f7533e0eab1e97cce97bb7ca1d3b
o.txt   321071  7dcd230890faf4ef848d4745eda14407
patching file o.txt
i.txt   321071  7dcd230890faf4ef848d4745eda14407
o.txt    46007  1da1f7533e0eab1e97cce97bb7ca1d3b

use of xargs to simplify mv requests

Not as funny, but nice anyway.

set -- {i,o}.txt t&&eval 'xargs -n2 mv<<<"' \${1,3,2,1,3,2} \"

Tags:

Code Golf