nix, shell, perl, php, mysql and mac os x tips and tricks

Wednesday, September 13, 2006

This might also work for forwarding e-mail

In the ~user HOME directory, add a file called: .forward
and put inside it this line:
forward@email.com
Then set the permissions to 600.

Making mail aliases at the server level

You can create an alias in /etc/aliases (or /etc/mail/aliases) on
the server like this:
aliasuser: forward@email.com
Then run 'newaliases'.

Tuesday, June 6, 2006

Import text into MySQL from command line

mysqlimport --fields-terminated-by=, --lines-terminated-by="\n" --user=user--password DATABASE TABLE_NAME.csv

Monday, April 24, 2006

ms sql for search-and-replace based on key/value table (not really tested)

    DECLARE @word1 varchar(1000)
     DECLARE @word2 varchar(1000)
     DECLARE word_cursor CURSOR LOCAL fast_forward FOR
     SELECT old_word, new_word FROM word_replace_table

     OPEN word_cursor

     FETCH NEXT FROM word_cursor INTO @word1, @word2

 WHILE @@FETCH_STATUS = 0

 BEGIN


   SET xact_abort ON
   BEGIN tran

   DECLARE @otxt varchar(1000)

   SET @otxt = @word1 /****/
   DECLARE @ntxt varchar(1000)

   SET @ntxt = @word2 /****/

   DECLARE @txtlen int
   SET @txtlen = len(@otxt)

   DECLARE @ptr BINARY(16)
   DECLARE @pos int
   DECLARE @id int
   DECLARE curs CURSOR LOCAL fast_forward
   FOR
   SELECT

   productId,
   textptr(description),
   charindex(@otxt, description)-1
   FROM
   product
   WHERE
   description
   LIKE
   '%' + @otxt +'%'

   OPEN curs

   FETCH NEXT FROM curs INTO @id, @ptr, @pos

   WHILE @@fetch_status = 0

   BEGIN

   print 'Text found in row id=' + cast(@id AS varchar) + ' at pos=' + cast(@pos AS varchar)

   updatetext product.description @ptr @pos @txtlen @ntxt

   FETCH NEXT FROM curs INTO @id, @ptr, @pos

   END

   CLOSE curs

   DEALLOCATE curs

   commit tran

     FETCH NEXT FROM word_cursor INTO @word1, @word2
 END

     CLOSE word_cursor
     DEALLOCATE word_cursor

Friday, April 7, 2006

clean ctrl-M chars from a file (be VERY careful with this one - better to test)

cat options.csv | sed "s/[^M]$//" > options1.csv

Tuesday, April 4, 2006

Shell script to make all files in directory lowercase

#!/bin/bash
for i in $(ls); do
    oldname="$i"
    newname=$(echo "$oldname" | tr 'A-Z' 'a-z')
    if [ "$oldname" != "$newname" ]
        then
            mv -i "$oldname" "$newname"
        fi
done

Thursday, March 30, 2006

Search and replace in MSSQL (specifically in TEXT field)

Just use Ctrl+Shft+M in Query Analyzer to replace the parameters. Then hit "play" in query analyzer til u don't get any more hits.
/*
*
* Search & Replace
*
* Use Ctrl+Shift+M to replace template values
*
*/

set xact_abort on
begin tran

declare @otxt varchar(1000)
set @otxt = ''

declare @ntxt varchar(1000)
set @ntxt = ''

declare @txtlen int
set @txtlen = len(@otxt)

declare @ptr binary(16)
declare @pos int
declare @id int

declare curs cursor local fast_forward
for
select
 id,
 textptr(),
 charindex(@otxt, )-1
from
 
where
 
like
 '%' + @otxt +'%'

open curs

fetch next from curs into @id, @ptr, @pos

while @@fetch_status = 0
begin
 print 'Text found in row id=' + cast(@id as varchar) + ' at pos=' + cast(@pos as varchar)
 
 updatetext  . @ptr @pos @txtlen @ntxt

 fetch next from curs into @id, @ptr, @pos 
end

close curs
deallocate curs

commit tran

Wednesday, March 1, 2006

Workaround for "argument list too long" error on 'nix

find /home/rory/backup/Mail/outbox/ -type f -name '*' -exec cp {} /home/rory/Mail/outbox/ \;

Monday, February 27, 2006

List only directories

ls -d */

Delete files older than x days

find /home/mysite/dir/ -type f -mtime +35 -exec rm {} \;

Monday, October 17, 2005

Extract a single directory from a tar.gz file

tar -zvxf myfile.tar.gz path/in/tarfile/to/extract

Wednesday, October 5, 2005

Purge mail from exim queue

mailq | awk '{print $3}' | xargs exim  -Mrm

Wednesday, September 21, 2005

Strip crtl-M characters from files on the command line (recurses)

find . -name '*.html' | xargs perl -pi -e 's/\r//g;'

Friday, July 15, 2005

File images in a horizontal or vertical subdirectory - uses ImageMagick

#!/usr/bin/perl

# check the image size and move to a horizontal
# or vertical subdirectory
use Image::Size;
use File::Copy;
use strict;

my $dir = "/home/rory/Jobs/images/cig_images/";
my $horiz = $dir . "horizontal";
my $vert = $dir . "vertical";

# read the files
opendir(DIR, $dir) || die "can't opendir $dir: $!";
my @images = readdir(DIR);
closedir(DIR);

# loop thru images
foreach my $image (@images) {
    my $fullpath = $dir . $image;
    if (not(-d $fullpath)) {    # exclude directories
       
        # check what dimension of the image is longer
        my ($x, $y) = imgsize("$fullpath");
        if ($x>$y) {
            move("$fullpath", "$horiz/$image") || die "move failed: $!";
        } else {
            move("$fullpath", "$vert/$image") || die "move failed: $!";   
        }
        print "$fullpath $x $y\n";
       
    } # end if for not a directory
   
} # end foreach loop thru images

Sunday, May 29, 2005

Using crypt to encrypt/decrypt files

A file can be encrypted in the shell mode using crypt, or in the edit mode using the -x or X option. When you are ready to decrypt the file, you can use the crypt command in the shell mode. The following is the command format to encrypt a file:
crypt < oldfile > newfile
The system prompts you for a password.



Before removing the unencrypted oldfile, make sure the encrypted newfile can be decrypted using the appropriate password.



To decrypt a file, redirect the encrypted file to a new file you can read. The command to decrypt a file is as follows:
crypt < encrypted_file > new_filename 

Monday, May 23, 2005

Use wget to retrieve a directory of mp3s

wget -r -l1 --no-parent -A.mp3 -R.html,.gif http://www.mysite.com/mp3/

Monday, May 9, 2005

Block a particular IP address with iptables

iptables -I INPUT -s 25.25.25.25 -j DROP

Thursday, March 3, 2005

In java, take a string and strip alphanumeric characters

Call it like this:
String newString = reformat(categoryName);
// for stripping strings of non alphanumeric stuff and replacing with +
// should really be a class

public String reformat(String categoryName)
{
StringBuffer reformattedString = new StringBuffer();
if (categoryName != null)
{
char[] chars = categoryName.toCharArray();
for (int ii = 0; ii < chars.length; ii++)
{
if (Character.isLetterOrDigit(chars[ii]))
{
reformattedString.append(chars[ii]);
}
else if (Character.isSpaceChar(chars[ii]))
{
if (reformattedString.length() > 0 && reformattedString.charAt(reformattedString.length() - 1) != '_')
{
reformattedString.append('_');
}
}
}
}
return reformattedString.toString();
}

Wednesday, March 2, 2005

Display last n lines of a file

tail -n /path/to/file

Tuesday, March 1, 2005

Parse IP from ifconfig with sed (excluding your internal IP)

/sbin/ifconfig | sed -n -e "s/^.*addr://g" -n -e "s/ Bcast.*//p" | grep -v '192.168.0.20'