Thursday, April 8, 2010

Handy Unix command line script

I don't use this very often, but it's one I keep in my head that I find really useful.

One thing you can use it for is to quickly make backup copies of files in a directory:

for i in `ls *.dbf`
do
cp $i $i.bkp
done

note the backticks, not single quotes in the first line.

You can also use it to change some text in all the files (probably worth taking a backup first):

for i in `ls *.sql`
do
sed 's/PROD/DEV/g' $i > $i,
mv $i, $i
done

Note the file is output to $i, then the $i, moved back over the original.

It can also be used if you copy files from Windows to Unix and they have "^M" at the end of each line:

for i in `ls *`
do
dos2unix $i > $i,
mv $i, $i
done

Ignore the "cannot get terminal type" messages.