Welcome

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

charpal - launch the Character Palette

/usr/bin/locate *CharPaletteServer.app

function charpal() {
   /usr/bin/open /System/Library/Components/CharacterPalette.component/Contents/SharedSupport/CharPaletteServer.app
   return 0
}


Get process ID (PID) via ps or killall

export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
export IFS=$' \t\n'

/usr/bin/sudo /bin/mkdir -p /usr/local/bin
/usr/bin/sudo /usr/sbin/chown root:wheel /usr/local /usr/local/bin
/usr/bin/sudo /bin/chmod 0755 /usr/local /usr/local/bin

ls -ld /usr/local /usr/local/bin

man killall | less -p 'Show only'
help kill

kill -l
kill -l 1 2 3 15

help type
type -t kill killall

# the -s option just triggers a fake kill
killall -s Finder
killall -s -HUP Finder
killall -s -9 Finder
killall -s -3 Finder


# cf. http://bashcurescancer.com/using-kill-to-see-if-a-process-is-alive.html
open -a 'Activity Monitor'
killall -s Terminal
kill -0 3832 &>/dev/null; echo $?           # no process with ID 3832 running if exit status is 1
echo TerminalPID=$(killall -s Terminal | awk '{print $NF}')
kill -0 $TerminalPID &>/dev/null; echo $?   # Terminal is alive
kill -0 $PPID &>/dev/null; echo $?          # Bash is alive


# kpid - get PID using killall -s

/bin/cat > ~/Desktop/kpid <<-'EOF'
#!/bin/sh

declare kpid rc

kpid=$(/usr/bin/killall -s -u $(/usr/bin/id -u) "${@}" 2>/dev/null)
rc=$?

if [[ $rc -eq 0 ]]; then
   printf "%s" "$kpid" | awk '{print $NF}'
else
   exit 1
fi

exit  0

EOF


/usr/bin/sudo /bin/mv -i ~/Desktop/kpid /usr/local/bin
/usr/bin/sudo /usr/sbin/chown root:wheel /usr/local/bin/kpid
/usr/bin/sudo /bin/chmod 0755 /usr/local/bin/kpid
/usr/bin/sudo /usr/bin/nano /usr/local/bin/kpid

open -a 'Activity Monitor'

kpid Finder
kpid Safari
kpid Dock
kpid TextEdit
kpid 'QuickTime Player'

kpid launchd
/usr/bin/sudo pid launchd

kpid cupsd; echo $?
/usr/bin/sudo kpid cupsd

kpid bash
/usr/bin/sudo kpid bash; echo $?

# kill Bash
#echo $PPID
#kill -HUP  $PPID
#kill -KILL $PPID


#---------------------------------------------------------------


# pspid - get PID using ps

/bin/cat > ~/Desktop/pspid <<-'EOF'
#!/bin/sh

declare pspid

if [[ "$1" = "-l" ]]; then

   #if [[ $# -eq 1 ]]; then /bin/ps -r -axco pid,command; exit 0; fi
   #if [[ $# -eq 1 ]]; then /bin/ps -axco pid,command | /usr/bin/sed '1,1d' | /usr/bin/sort -rn ; exit 0; fi
   if [[ $# -eq 1 ]]; then /bin/ps -axco pid,command | /usr/bin/sed '1,1d' | /usr/bin/sort -n ; exit 0; fi

   #pspid="$(/bin/ps -axco pid,command | /usr/bin/awk "/${2}/ { print \$1,\$2 }")"
   #printf "%-15s %-15s\n" $(printf "%s" "$pspid" | /usr/bin/sort -n)
   
   #pspid="$(/bin/ps -axco pid,command,uid | /usr/bin/awk "/${2}/ { print \$1,\$2,\$3 }")"
   #printf "%-20s %-20s %-20s\n" $(printf "%s" "$pspid" | /usr/bin/sort -n)

   pspid="$(/bin/ps -axco pid,command,uid,user | /usr/bin/awk "/${2}/ {print \$1,\$2,\$3,\$4}")"
   printf "%-20s %-20s %-20s %-20s\n" $(printf "%s" "$pspid" | /usr/bin/sort -n)

   exit 0

fi

pspid="$(/bin/ps -axco pid,command | /usr/bin/awk "/${@}/ {print \$1}")"

if [[ -n "$pspid" ]]; then
   printf "%s\n" "$pspid"
else
   exit 1
fi

exit  0

EOF


/usr/bin/sudo /bin/mv -i ~/Desktop/pspid /usr/local/bin
/usr/bin/sudo /usr/sbin/chown root:wheel /usr/local/bin/pspid
/usr/bin/sudo /bin/chmod 0755 /usr/local/bin/pspid
/usr/bin/sudo /usr/bin/nano /usr/local/bin/pspid

open -a 'Activity Monitor'

pspid Finder
pspid Safari
pspid TextEdit
pspid 'QuickTime Player'
pspid login
pspid dynamic_pager
pspid launchd
pspid bash
echo $PPID

pspid -l
pspid -l login
pspid -l launchd
pspid -l bash
pspid -l '.*[sS]erver.*'
pspid -l '.*d$'
pspid -l '.*' | grep nobody
pspid -l '.*' | grep root

Handling control characters on the command line

# cf. http://en.wikipedia.org/wiki/Control_character and 
# http://ascii.cl/control-characters.htm

printf '\033'"\n" | cat -vet -
printf '\x0d'"\n" | cat -vet -

[ctrl-v][esc]
[ctrl-v][ctrl-m]

printf '[ctrl-v][ctrl-m]' | cat -vet -; echo


# cf. http://codesnippets.joyent.com/posts/show/1630
printf !:1 | sed -n -e 'l' 

# for an alternative to !:1 try [esc][ctrl][y]
printf !:1 | pbcopy    

# cf. man ascii
printf $(pbpaste) | od -A n -b
printf $(pbpaste) | od -A n -t xC
printf $(pbpaste) | od -A n -t dC

printf $(pbpaste) | od -A n -c
printf $(pbpaste) | od -A n -a

echo $'hel\rlo' 
echo $'hel\rlo' | sed s/[ctrl-v][ctrl-m]//
echo $'hel\rlo' | sed 's/[ctrl-v][ctrl-m]//'
echo $'hel\rlo' | sed "s/[ctrl-v][ctrl-m]//"
echo $'hel\rlo' | sed s/$'[ctrl-v][ctrl-m]'//


man infocmp
infocmp --help

infocmp -1 | grep '\^'
infocmp -1 | grep '\<k'
infocmp -L1 | grep '\^'
infocmp -I1 | grep '\^'
infocmp -C1 | grep '\^'


tput cup 0 0
tput cup 0 0 | cat -vet -; echo
tput cup 0 0 | sed -n -e 'l'
tput cup 0 0 | od -A n -c | sed '$,$d'
tput cup 0 0 | od -A n -a | sed '$,$d'
tput cup 0 0 | od -A n -b | sed '$,$d'
tput cup 0 0 | od -A n -t xC | sed '$,$d'

tput sgr0 | cat -vet -; echo
tput cuu | cat -vet -; echo
tput up | cat -vet -; echo
tput dl1 | cat -vet -; echo

tput kbs | wc -c
tput kbs | ruby -n -e 'p $_.to_s'


printf "%s\000\n" "str" | cat -vet -
printf "%s\000\n" "str" | od -A n -b | sed '$,$d'
printf "%s\000\n" "str" | sed -n -e 'l'
printf "%s\000\n" "str" | ruby -n -e 'p $_.to_s'

Handling file names with initial dash character

export PATH=/usr/bin:/bin:/usr/sbin:/sbin
export IFS=$' \t\n'

mkdir -p ~/Desktop/TestDir
touch ~/Desktop/TestDir/file{1,2,3,4,5}.txt
open ~/Desktop/TestDir

cd ~/Desktop/TestDir

touch -i

touch ~/Desktop/TestDir/-i

touch -- -i
chmod 000 -i
touch -- --i.txt
chmod 000 --i.txt

rm -f -i
rm -f -i -R *

rm -f -- -i
rm -f -- --i.txt

#rm -f ./-i
#rm -f ./--i.txt

rm -f -i -R *

Javascript String Replace

just like php's str_replace

var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace("username", visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

flip - newline conversion tool

export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
export IFS=$' \t\n'

# download & install flip
cd ~/Desktop
curl -L -O http://ccrma-www.stanford.edu/~craig/utility/flip/flip.osx
mv ~/Desktop/flip.osx ~/Desktop/flip
/usr/bin/sudo /bin/cp -ip ~/Desktop/flip /usr/bin
/usr/bin/sudo /usr/sbin/chown root:wheel /usr/bin/flip
/usr/bin/sudo /bin/chmod +x /usr/bin/flip
ls -l /usr/bin/flip

flip
flip -t /path/to/file     # display current file type
flip -u /path/to/file     # convert to Unix: "\n"
flip -d /path/to/file     # convert to MS-DOS/Windows: "\r\n"
flip -m /path/to/file     # convert to Macintosh (OS 9): "\r"


#----------------------------------


# create a test file

testfile="${HOME}/Desktop/testfile.txt"

function createfile() {
   testfile="${HOME}/Desktop/testfile.txt"
   /usr/bin/jot -b 'sample text' 10 | /bin/cat -n > "$testfile"
   # append a line with a '\r\n' line separator
   printf "%s\r\n\r\n\r\r\n" "sample text" >> "$testfile"      
   # append a last line without a terminating '\n'
   printf "%s" "sample text" >> "$testfile"          
   return 0
}


function odcfile() {

/usr/bin/od -A n -c < "$@" | /usr/bin/sed -E -e 's/^[[:space:]]{11}//' \
       -e s/[[:space:]]{4}/$'\001'/g \
       -e 's/[[:space:]]+//g' | \
       /usr/bin/tr -d '\n' | /usr/bin/tr '\001' ' ' | \
       /usr/bin/sed -e s/\\\\n/$'\\\\\\n\\\n'/g 

return 0
}


createfile
odcfile "$testfile"
flip -t "$testfile"     # display current file type

flip -d "$testfile"     # convert to MS-DOS/Windows: "\r\n"
flip -t "$testfile"
odcfile "$testfile"

flip -m "$testfile"     # convert to Macintosh (OS 9): "\r"
flip -t "$testfile"
odcfile "$testfile"

flip -u "$testfile"     # convert to Unix: "\n"
flip -t "$testfile"
odcfile "$testfile"

Install ikiwiki in an arbitrary directory

ikiwiki doesn't install using PREFIX= like normal programs (it still wants to put stuff in /etc/ikiwiki).

perl Makefile.PL DESTDIR=/path/to/install/dir PREFIX="" INSTALL_BASE="/"

Fire Event With Listener

If you need to fire off an event but it is currently handled by an event listener.

more information here http://www.howtocreate.co.uk/tutorials/javascript/domevents


var fireOnThis = document.getElementById('someID');
if( document.createEvent ) {
  var evObj = document.createEvent('MouseEvents');
  evObj.initEvent( 'mousemove', true, false );
  fireOnThis.dispatchEvent(evObj);
} else if( document.createEventObject ) {
  fireOnThis.fireEvent('onmousemove');
}

Javascript Event Listeners

Add event listeners for all browsers at once.
##
Not my own code but works like a charm!
##
//*** This code is copyright 2003 by Gavin Kistner, gavin@refinery.com
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//*** Reuse or modification is free provided you abide by the terms of that license.
//*** (Including the first two lines above in your source code satisfies the conditions.)


//***Cross browser attach event function. For 'evt' pass a string value with the leading "on" omitted
//***e.g. AttachEvent(window,'load',MyFunctionNameWithoutParenthesis,false);

function AttachEvent(obj,evt,fnc,useCapture){
	if (!useCapture) useCapture=false;
	if (obj.addEventListener){
		obj.addEventListener(evt,fnc,useCapture);
		return true;
	} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
	else{
		MyAttachEvent(obj,evt,fnc);
		obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
	}
} 

//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
	if (!obj.myEvents) obj.myEvents={};
	if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
	var evts = obj.myEvents[evt];
	evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
	if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
	var evts = obj.myEvents[evt];
	for (var i=0,len=evts.length;i<len;i++) evts[i]();
}

Delete carriage returns & newlines with sed

# delete newlines

printf "a\nb\nc\nd\ne\nf" | sed -n -e 'l'
printf "a\nb\nc\nd\ne\nf" | sed -E -e :a -e '$!N; s/\n//g; ta'

printf "a\n\nb" | sed -n -e 'l'
printf "a\n\nb" | sed -E -e :a -e '$!N; s/\n//g; ta' | sed -n -e 'l'
printf "a\n\nb" | sed -E -e :a -e '$!N; s/\n$//g; ta' | sed -n -e 'l'
printf "a\n\n\n\n\n\nb" | sed -E -e :a -e '$!N; s/\n$//g; ta' | sed -n -e 'l'


# delete carriage returns

printf "he\r\rllo\n" | sed -n -e 'l'
printf "he\r\rllo\n" | sed -e s/$'\r'//g | sed -n -e 'l'
printf "he\r\rllo\n" | sed -e s/$'\r\r'/$'\r'/g | sed -n -e 'l'

CR=$'\r'
printf "hello\r\r\n" | sed "s/$CR$CR$/$CR/g" | sed -n -e 'l'


# alternatives

printf "a\nb\nc\nd\ne\nf" | tr -d '\n'

# cf. http://linux.dsplabs.com.au/rmnl-remove-new-line-characters-tr-awk-perl-sed-c-cpp-bash-python-xargs-ghc-ghci-haskell-sam-ssam-p65/
while read -d $'\n'; do echo -n "${REPLY} "; done < <((printf "a\nb\nc\nd\ne\nf"))
while read -d $'\n'; do printf "%s   " "${REPLY}"; done < <((printf "a\nb\nc\nd\ne\nf"))

xargs echo < <((printf "a\nb\nc\nd\ne\nf"))
xargs printf "%s " < <((printf "a\nb\nc\nd\ne\nf"))

printf "a\nb\nc\nd\ne\nf" | /usr/bin/paste -s -d ' ' -     # cf. man paste

# delete newlines in-place (also see below)
vim -e -s +':%j' +'w!' +'qa!' /path/to/file

# insert newlines again
printf "%s\n" "hello" | sed -e s/l/$'\\\n'/g | sed -n -e 'l'
printf "%s\n" "hello" | sed -E s/\(l\)/\\1$'\\\n'/g | sed -n -e 'l'


#-----------------------------------------------------------


# converting between \n and \n\r

# cf. also flip, http://ccrma.stanford.edu/~craig/utility/flip/ and 
# http://codesnippets.joyent.com/posts/show/1660


# convert \n into \r\n
printf "a\nb\nc\nd\ne\nf\n"
printf "a\nb\nc\nd\ne\nf\n" | sed -n -e 'l'

printf "a\nb\nc\nd\ne\nf\n" | sed s/$/$'\r'/
printf "a\nb\nc\nd\ne\nf\n" | sed s/$/$'\r'/ | sed -n -e 'l'

printf "a\nb\n\n\n\n\n\n\n\n\n\n\nc\nd\ne\nf\n" | sed -E -e :a -e '$!N; s/\n$//g; ta' | sed -E s/$/$'\r'/ | sed -n -e 'l'

while read -d $'\n'; do printf "%s\r\n" "${REPLY}"; done < <((printf "a\nb\nc\nd\ne\nf\n"))
while read -d $'\n'; do printf "%s\r\n" "${REPLY}"; done < <((printf "a\nb\nc\nd\ne\nf\n")) | sed -n -e 'l'


# convert \r\n into \n
printf "a\r\nb\r\nc\r\nd\r\ne\r\nf\r\n"
printf "a\r\nb\r\nc\r\nd\r\ne\r\nf\r\n" | sed -n -e 'l'

printf "a\r\nb\r\nc\r\nd\r\ne\r\nf\r\n" | sed s/$'\r'$//
printf "a\r\nb\r\nc\r\nd\r\ne\r\nf\r\n" | sed s/$'\r'$// | sed -n -e 'l'

printf "a\r\nb\r\r\r\r\r\r\r\r\r\r\nc\r\nd\r\ne\r\nf\r\n" | sed s/$'\r'*$// | sed -n -e 'l'
printf "a\r\nb\r\r\r\r\r\r\r\r\r\r\nc\r\nd\r\ne\r\nf\r\n" | sed -E s/$'\r'+$// | sed -n -e 'l'

# lacks a terminating \n though
while read -d $'\r'; do printf "%s" "${REPLY}"; done < <((printf "a\r\nb\r\nc\r\nd\r\ne\r\nf\r\n"))
while read -d $'\r'; do printf "%s" "${REPLY}"; done < <((printf "a\r\nb\r\nc\r\nd\r\ne\r\nf\r\n")) | sed -n -e 'l'


#---------------------------------------


# create test files

testfile="${HOME}/Desktop/testfile.txt"
output="${HOME}/Desktop/output.txt"

function createfiles() {

testfile="${HOME}/Desktop/testfile.txt"
output="${HOME}/Desktop/output.txt"

/usr/bin/touch "$output"

#/usr/bin/jot -b 'sample text' 10 | /bin/cat > "$testfile"
/usr/bin/jot -b 'sample text' 10 | /bin/cat -n > "$testfile"
printf "%s\r\n\r\n\r\r\n" "sample text" >> "$testfile"      # append a line with a '\r\n' line separator
printf "%s" "sample text" >> "$testfile"          # append a last line without a terminating '\n'

return 0
}

createfiles


# inspect test file

cat -vet "$testfile"
ed -s "$testfile" <<< $',l'
sed -n -e 'l'  "$testfile"
ruby -n -e 'p $_.to_s' < "$testfile"


function odcfile() {

/usr/bin/od -A n -c < "$@" | /usr/bin/sed -E -e 's/^[[:space:]]{11}//' \
       -e s/[[:space:]]{4}/$'\001'/g \
       -e 's/[[:space:]]+//g' | \
       /usr/bin/tr -d '\n' | /usr/bin/tr '\001' ' ' | \
       /usr/bin/sed -e s/\\\\n/$'\\\\\\n\\\n'/g 

return 0
}


odcfile "$testfile"


# remove newlines "\n"

# create a new file with newline characters replaced with a space
sed -e :a -e '$!N; s/\n/ /g; ta' "$testfile" > "$output"
odcfile "$output"

# same, but in-place
sed -i "" -e :a -e '$!N; s/\n/ /g; ta' "$testfile"
odcfile "$testfile"

createfiles

# delete newlines in-place
sed -i "" -e :a -e '$!N; s/\n//g; ta' "$testfile"
odcfile "$testfile"

createfiles

# alternative for creating a new file without newlines
tr -d '\n' < "$testfile" > "$output"
odcfile "$output"



# delete carriage returns "\r"

# create a new file with carriage returns deleted
sed -e s/$'\r'//g "$testfile" > "$output"
sed -e s/$'\r'$//g "$testfile" > "$output"  # only at line end
odcfile "$output"

# alternative
tr -d '\r' < "$testfile" > "$output"
odcfile "$output"


# delete carriage returns in-place

sed -i "" -e s/$'\r'//g "$testfile" > "$output"
odcfile "$testfile"

createfiles

# cf. http://bash-hackers.org/wiki/doku.php?id=howto:edit-ed (Pitfalls)
ed -s "$testfile" <<< $'H\n,g/\r/s/\r//\n,w'      # delete one carriage return in a line
ed -s "$testfile" <<< $'H\n,g/\r/s/\r//g\n,w'     # delete all carriage returns in a line
ed -s "$testfile" <<< $'H\n,g/\r$/s/\r$//g\n,w'   # delete a carriage return at line end

odcfile "$testfile"



printf "\n" | od -A n -c
printf "\012" | od -A n -c
printf "\x0a" | od -A n -c

printf '[ctrl-v][ctrl-j]' | od -A n -c      #  \n or ^J


printf "\r" | od -A n -c
printf "\015" | od -A n -c
printf "\x0d" | od -A n -c

printf '[ctrl-v][ctrl-j]' | od -A n -c      #  \r or ^M


# vim
createfiles

vim "$testfile"
#...
:set number
:set list
:%s/^M//g
:set fileformat=unix
#:set fileformat=dos
:x

odcfile "$testfile"


# edit files in-place with vim

createfiles

# delete newlines in-place
vim -e -s +':%j' +'w!' +'qa!' "$testfile"
odcfile "$output"

createfiles

# replace every \r with \n
# cf. http://vim.wikia.com/wiki/Change_end-of-line_format_for_dos-mac-unix
vim -e -s +':%s/\r/\r/g' +':set fileformat=unix' +'w!' +'qa!' "$testfile"
odcfile "$output"

createfiles

# delete every \r
vim -e -s +':%s/\r//g' +':set fileformat=unix' +'w!' +'qa!' "$testfile"
odcfile "$output"

createfiles

# delete \r only when it occurs at the end of a line
vim -e -s +':%s/\r$//g' +':set fileformat=unix' +'w!' +'qa!' "$testfile"
odcfile "$output"

createfiles

# replace carriage return line endings with \n
# cf. Getting rid of ^M - mixing dos and unix, http://www.vim.org/tips/tip.php?tip_id=26
printf "\r" >> "$testfile"
vim -e -s +':g/\r$/s///g' +':set fileformat=unix' +'w!' +'qa!' "$testfile"
odcfile "$testfile"

createfiles

# delete last \n of file
vim -e -s +':set noeol bin' +':set fileformat=unix' +'w!' +'qa!' "$testfile"
odcfile "$output"

createfiles

# change mixed mode files to DOS mode
#vim -e -s +':%s/\r\r/\r/g' +'w!' +'qa!' "$testfile"
sed -i '' -e s/$'\r\r'/$'\r'/g  "$testfile"
vim -e -s +':e ++ff=dos' +'w!' +'qa!' "$testfile"
vim -e -s +':e ++ff=dos' +':set ff=dos' +'w!' +'qa!' "$testfile"
odcfile "$output"

vim "$testfile"
:set ff?
:x