Never been to CodeSnippets before?

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!)

kv - launch Keyboard Viewer

locate -i *keyboardviewerserver

alias kv='/usr/bin/open /System/Library/Components/KeyboardViewer.component/Contents/SharedSupport/KeyboardViewerServer.app'

kv


# cf. Accented letters and other symbols on the Mac,
# http://mac4translators.blogspot.com/2008/08/accented-letters-and-other-symbols-on.html

[cmd]     #  hold the command key
[alt]
[alt][shift]

pcregrep - UTF-8 aware grep replacement

# we first have to download, compile & install the PCRE library, cf. http://www.pcre.org/pcre.txt
# requirement: Xcode, http://developer.apple.com/tools/xcode/index.html

cd ~/Desktop
/usr/bin/curl -L -O http://downloads.sourceforge.net/pcre/pcre-7.7.tar.gz
/usr/bin/tar -xzf pcre-7.7.tar.gz
cd pcre-7.7
./configure --help
./configure --prefix=/usr/local --enable-utf8 --enable-unicode-properties
# for Intel Macs, see http://hivelogic.com/articles/2005/12/ruby_rails_lighttpd_mysql_tiger
#./configure --prefix=/usr/local --enable-utf8 --enable-unicode-properties CFLAGS=-O1
/usr/bin/make
/usr/bin/sudo /usr/bin/make install 


ls -l /usr/local/bin/pcregrep
stat -x /usr/local/bin/pcregrep

pcregrep --version
pcregrep --help
pcregrep --help | pcregrep -i 'utf-?8'
pcregrep --help | pcregrep -i multiline

man pcregrep
man pcrepattern
man pcretest
man perlretut

man pcregrep | less -p utf-8
man pcregrep | less -p multiline
man perlretut | less -p 'single line and multi'

open /usr/local/share/doc/pcre/html/pcregrep.html


# check if character set encoding of Terminal.app is set to UTF-8
if [[ "$(/usr/bin/defaults read com.apple.Terminal StringEncoding)" != "4" ]]; then 
   echo 'Terminal.app does not use UTF-8 character set encoding!'
   exit 1
fi


utf8str=$'caf\303\251'

printf $utf8str | /usr/bin/egrep -o '.'
printf $utf8str | /usr/local/bin/pcregrep -o '.'
printf $utf8str | /usr/local/bin/pcregrep -ou '.'     # UTF-8 aware

printf $utf8str | /usr/bin/egrep -o '.' | wc -l
printf $utf8str | /usr/local/bin/pcregrep -o '.' | wc -l
printf $utf8str | /usr/local/bin/pcregrep -ou '.' | wc -l     # UTF-8 aware

Tapping the Bash command line history

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


help fc
help history
help bind
help set
help shopt
open /usr/share/doc/bash/builtins.pdf


cp -ip ~/.bashrc ~/.bashrc.orig
cp -ip ~/.inputrc ~/.inputrc.orig
cp -ip ~/.bash_history ~/.bash_history.bak

cp -ip ~/.bashrc{,.orig}  # shortcut version
cp -ip ~/.inputrc{,.orig}
cp -ip ~/.bash_history{,.bak}


history
history | head -n 3
history | tail -n 1
history | egrep 5
history | egrep '^[[:space:]]*5'
history | egrep -m 1 '^[[:space:]]*5'
history | egrep '^[[:space:]]*5[[:space:]]+'

fc
fc -e nano
fc -l | nl
fc -ln | sed 's/^[[:space:]]*//'
fc -l 0
fc -l 1 -1
#exec /bin/bash     # ... in case of "fc: history specification out of range"
#source ~/.bash_login
fc -l -1
fc -l -5
fc -l 5 "cd "
fc -l -r 5 "cd "
fc -l -5 | grep cd | awk '{print $1}'
fc -s cd     # execute last cd command
fc -e vim 3
fc -e nano "cd "


set +o history   # disable adding commands to history list
set -o history   # enable adding commands to history list


/bin/cat >> ~/.bashrc <<-'EOF'

bind Space:magic-space     # enable option to expand & edit a command before running it by entering a [space]
#shopt -s histverify     # expand & edit a command before running it by entering [return]
shopt -s cmdhist
shopt -s histappend

# suppress history recording for the specified commands including commands beginning with a space
export HISTIGNORE="&:[ \t]*:ls:[bf]g:history*:clear:exit"

#export HISTCONTROL=ignorespace
#export HISTCONTROL=ignoredups
#export HISTCONTROL=ignoreboth

#PROMPT_COMMAND="history -a; ${PROMPT_COMMAND}"

EOF

source ~/.bashrc


/bin/cat >> ~/.inputrc <<-'EOF'

"\033[3~": delete-char             # get a proper forward delete key in Terminal.app
"\e[A": history-search-backward    # search command history backward with up arrow key
"\e[B": history-search-forward     # search command history forward with down arrow key

set show-all-if-ambiguous on        # enable tab completion with a single tab
set mark-symlinked-directories on
set completion-ignore-case on
#set visible-stats on
#set bell-style visible

#$if Bash   # same effect as "bind Space:magic-space" in ~/.bashrc
#  Space: magic-space
#$endif

EOF


exec /bin/bash    # reinitialize ~/.inputrc
source ~/.bash_login ~/.bashrc


help bind
bind -l | less
bind -P | less
bind -p | less    
bind -V | less
bind -v | less


# insert the last word of the previous command line
echo hello world1
echo hello world1 and world2
echo hello world1 and world2 and world3
echo hello
echo

[esc-.]     # press the esc-. key sequence repeatedly to iterate through the history list
[ctrl-u]    # clear the current command line
echo !$
printf "%s\n" $_


!1[space]            # expand the first command in the history list without executing
!12[space]           # expand command no. 12
sudo !![space]       # expand last command
!-4[space]           # expand the fourth last command
!cd[space]           # expand the last cd command
!?world?[space]      # expand the last command containing the specified word
!$[space]            # last word of the preceding command line
!:1[space]           # first argument of the preceding command
!-1:1[space]         # same
!-1:1-[space]        # all arguments of the previous command except the last on
!-1:1*[space]        # all arguments of the previous command
!-1:1-$[space]       # same
!-2:3[space]         # third argument from the command before the last one

abc def !#[space]     # double the entire command line typed so far

cd ~/Desktop
!cd:p
!cd[space]
[ctrl-u]
!?cd?:p                 # make the last cd command the last command in the history list and print it without executing
history | tail -n 1

cd[up_key]    
cp[up_key]              # hit the up & down arrow keys again and again to iterate through the commands
cp[down_key]           

[ctrl-r]cp              # press ctrl-r repeatedly to iterate through the previous commands
[esc] or [ctrl-j]       # quit searching with ctrl-r
[ctrl-k] + [ctrl-u]     # quit searching with ctrl-r and clear the command line
[ctrl-y]                # recalls the last string removed by ctrl-k or ctrl-u


# cf. http://nubyonrails.com/articles/2007/05/26/useful-shell-shortcuts
cp foo !#^.bak[space]            # !#^ refers to the first word after the command
cp -i foo !#^.bak[space]    
cp -p -i foo !#^.bak[space]    
cp !#$.bak[space] 
cp foo !#$.bak[space]            # !#$ refers to the preceding word
cp -i foo !#$.bak[space]    
echo abc def !#$.bak[space]
echo abc def !#$.bak ghi jkl !#$.foo mno[space]


# tab completion
#[tab]  # all available commands
#ds[tab]  # all available commands beginning with ds
#cd ~/Desktop
#cd ~/Des[tab]
#$[tab]  # all set system variables
#~[tab]  # users
#*[tab] 
#=[tab]
#/[tab]

Edit multiple lines on the command line

export EDITOR=nano
[ctrl-x-e]   # press ctrl-x-e keys


help fc
open /usr/share/doc/bash/builtins.pdf

fc     # edit last command in $EDITOR
fc -l 3 5  
fc 4     # edit command no. 4
fc -2
fc "cd "     # edit last cd command

fc -e vim     # edit last command in vim
fc -e vim "cd "
fc -e vim 4    

"openterminal" contextual menu item with Automator

Right-click on a file or folder in a Finder window and select Automator -> openterminal to open it in Terminal.app.
(i.e. cd to the folder or open the file in the nano text editor)

open -a Automator

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

Drag or add actions here to build your workflow:
Library: Finder -> Action: Get Selected Finder Items
Library: Automator -> Action: Run Shell Script
                                 - Shell: /bin/sh
                                 - Pass input: as arguments


if [[ $# -gt 1 ]]; then exit 0; fi

if [[ -d "$@" ]]; then

   printf "%s" "$@" | /usr/bin/pbcopy
   #/usr/local/bin/cpath # cf. http://osxutils.sourceforge.net

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; cd \"$(/usr/bin/pbpaste)\"; /usr/bin/clear" in (first window whose name contains " ")'

# alternative without /usr/bin/clear (experimental)
# requires:
# defaults write com.apple.Terminal Autowrap NO
# or:
# Terminal menu -> Window Settings ...  -> Buffer -> in the Scrollback 
# section check the box next to "Wrap lines that are too long" 
# -> click "Use Settings as Defaults"

#   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "cd \"$(/usr/bin/pbpaste)\"; /usr/bin/tput cup 0 0; /usr/bin/tput dl1; /usr/bin/tput el; /usr/bin/tput dl1; /usr/bin/tput el" in (first window whose name contains " ")'

   exit 0

elif [[ -r "$@" ]]; then 

   printf "%s" "$@" | /usr/bin/pbcopy

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; /usr/bin/clear; /bin/sleep 0.3; /usr/bin/nano \"$(/usr/bin/pbpaste)\";" in (first window whose name contains " ")'

exit 0

fi

exit 0


# now save the openterminal Automator workflow as a contextual menu item:
# Automator -> File -> Save As Plug-in ... -> Save Plug-in As: openterminal -> Plug-in for: Finder -> click Save


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


open -a Automator ~/Library/Workflows/Applications/Finder/openterminal.workflow

/usr/bin/automator ~/Library/Workflows/Applications/Finder/openterminal.workflow >/dev/null 2>&1


More on how to cd effectively:

- cdto - Finder Toolbar button to open a Terminal window
- History of visited directories in BASH
- bash Tips and Tricks: $CDPATH
- Bash Shell Customisation: cdable_vars
- The Definitive Guide to Bash Command Line History
- Working Productively in Bash's Vi Command Line Editing Mode (with Cheat Sheet)
- Leopard's bash auto-completion vs. symlinked directories
- cd to Directory within Terminal
- Pimp my shell
- Per-directory bash history
- Terminal Tricks: A Fuzzy cd Command
- recd on sourceforge
- recd - cd again via regular expression
Download with: curl -L -O http://heanet.dl.sourceforge.net/sourceforge/recd/recd.sh

Change package names of java files

changes the package names of java classes.

For example, if you have a bunch of java files in a package and you need to move them to a new package.

#!/bin/sh
                          
for file in `ls *.java` 
do
  sed -e "s/old.package.name/new.package.name/" $file > /tmp/tempfile.tmp
  mv /tmp/tempfile.tmp $file
done

Recursive grep without grep -r

Bumped into this situation recently on a Solaris system. I wanted to do a recursive grep, using the -r flag. That flag is not standard, so I was stuck until I whipped up this little diddy.

After navigating to the directory that you want as the root of the search, enter
find . -type f -exec grep <pattern> {} \;

It will only show the entries that match that pattern. Don't forget that you can also add in addition filters to the find command to limit the search file types, if so needed. So, by way of example, if you wanted to find every time you used the word Vista in your home directory, open up the command line and enter:
[user@host ~]$ find . -type f -exec grep Vista {} \;

My search returned nothing ;-)

airport

# For more information see:
# airport - the Little Known Command Line Wireless Utility,
# http://osxdaily.com/2007/01/18/airport-the-little-known-command-line-wireless-utility/

/usr/bin/sudo /bin/ln -s /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport /usr/sbin/airport

airport -help
airport -I
airport -S
airport -s

month & day

# cf. http://www.macgeekery.com/tips/cli/a_neat_bash_one-liner

function month() {
#/usr/bin/cal | sed -E -e 's/^/  /' -e 's/$/  /' -e "s/ $(/bin/date +%e) /$(printf '\e[1m&\e[m')/" 
#/usr/bin/cal | sed -E -e 's/^/  /' -e 's/$/  /' -e "s/ $(/bin/date +%e) /$(printf '\e[1;31m&\e[m')/" 
#/usr/bin/cal | sed -E -e 's/^/  /' -e 's/$/  /' -e "s/ $(/bin/date +%e) /$(printf '\e[1;32m&\e[m')/" 
#/usr/bin/cal | sed -E -e 's/^/  /' -e 's/$/  /' -e "s/ $(/bin/date +%e) /$(printf '\e[1;33m&\e[m')/" 
#/usr/bin/cal | sed -E -e 's/^/  /' -e 's/$/  /' -e "s/ $(/bin/date +%e) /$(printf '\e[1;34m&\e[m')/" 
#/usr/bin/cal | sed -E -e 's/^/  /' -e 's/$/  /' -e "s/ $(/bin/date +%e) /$(printf '\e[1;35m&\e[m')/" 
/usr/bin/cal | sed -E -e 's/^/  /' -e 's/$/  /' -e "s/ $(/bin/date +%e) /$(printf '\e[1;36m&\e[m')/" 
return 0
}

month

alias day=month
day

How to keep the list of completed print jobs empty

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

echo 'Hello, world!' | enscript -q -B --word-wrap -f Helvetica30 -p - | lpr

/usr/bin/lpstat -W completed
/usr/bin/lpstat -W not-completed

# clear the whole print queue
#/usr/bin/cancel -a -    

# remove individual print jobs from the queue
defaultprinter=$(/usr/sbin/system_profiler SPPrintersDataType | egrep -B 5 'Default: Yes' | head -n 1 | sed -e 's/^[[:space:]]*//' -e 's/:$//')
alias opendefaultprinter='/usr/bin/open -a "$defaultprinter"'

opendefaultprinter


man 5 cupsd.conf

# make a backup of cupsd.conf
/usr/bin/sudo /bin/cp -p /private/etc/cups/cupsd.conf /private/etc/cups/cupsd.conf.orig  

# get line numbers of matching lines
sed -E -n -e '/cups/=' /private/etc/cups/cupsd.conf
sed -E -n -e '/^#PreserveJobHistory[[:space:]]+Yes/=' /private/etc/cups/cupsd.conf
sed -E -n -e '/^[[:space:]]*PreserveJobHistory[[:space:]]+Yes/=' /private/etc/cups/cupsd.conf
sed -E -n -e '/^[[:space:]]*PreserveJobHistory[[:space:]]+No/=' /private/etc/cups/cupsd.conf

open -e /private/etc/cups/cupsd.conf
nano /private/etc/cups/cupsd.conf


# disable PreserveJobHistory in cupsd.conf
/usr/bin/sudo /bin/ed -s /private/etc/cups/cupsd.conf <<< $',s|^#*PreserveJobHistory Yes|PreserveJobHistory No|\nw'

/usr/bin/sudo /usr/bin/killall -HUP cupsd    # reload cupsd.conf

# enable PreserveJobHistory in cupsd.conf
/usr/bin/sudo /bin/ed -s /private/etc/cups/cupsd.conf <<< $',s|^[[:space:]]*PreserveJobHistory No|PreserveJobHistory Yes|\nw'

/usr/bin/sudo /usr/bin/killall -HUP cupsd


# Mac OS X 10.5: Removing information about completed print jobs,
# http://support.apple.com/kb/HT1857
# http://developer.apple.com/documentation/Darwin/Reference/ManPages/man8/cupsctl.8.html

man 8 cupsctl
cupsctl PreserveJobHistory=No
cupsctl PreserveJobHistory=Yes