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

Edit multiple lines on the command line

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

"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
- 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

Create & print PDF files from the command line on Mac OS X

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

open -a 'Printer Setup Utility'

man 8 system_profiler
/usr/sbin/system_profiler  -listDataTypes
/usr/sbin/system_profiler SPPrintersDataType


defaultprinter=$(/usr/sbin/system_profiler SPPrintersDataType | egrep -B 5 'Default: Yes' | head -n 1 | sed -e 's/^[[:space:]]*//' -e 's/:$//')
printf "%s\n" "$defaultprinter"
lpstat -d | awk '{print $NF}'
alias opendefaultprinter='/usr/bin/open -a "$defaultprinter"'

opendefaultprinter


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

/usr/bin/jot -b 'This is a test sentence!' 10 | cat -n > "$testfile"
open -e "$testfile"

/usr/bin/enscript -p ~/Desktop/testfile.ps "$testfile"
open ~/Desktop/testfile.ps

/usr/bin/enscript -p - "$testfile" | lpr 
opendefaultprinter


# use Bash process substitution instead of ~/Desktop/testfile.txt
# cf. http://wooledge.org:8000/ProcessSubstitution,
# http://wooledge.org:8000/BashFAQ (FAQ 20 & 24) and
# http://tldp.org/LDP/abs/html/process-sub.html

ls -l <((/usr/bin/jot -b 'This is a test sentence!' 10))
stat -x <((/usr/bin/jot -b 'This is a test sentence!' 10))
cat -n <((/usr/bin/jot -b 'This is a test sentence!' 10))

/usr/bin/enscript -p ~/Desktop/testfile.ps <((/usr/bin/jot -b 'This is a test sentence!' 10))
open ~/Desktop/testfile.ps

enscript -p - <((/usr/bin/jot -b 'This is a test sentence!' 10)) | lpr 
opendefaultprinter


man pstopdf
man enscript
enscript --help
enscript --list-media
enscript --list-options


/usr/bin/enscript -p ~/Desktop/testfile.ps "$testfile"
/usr/bin/pstopdf ~/Desktop/testfile.ps
open ~/Desktop/testfile.pdf

/usr/bin/enscript -p - "$testfile" | /usr/bin/pstopdf -i -o ~/Desktop/test.pdf
open ~/Desktop/test.pdf

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

lpstat -d
lpstat -W completed
lpstat -W not-completed
lpq -a
lpq -P $(/usr/bin/lpstat -d | /usr/bin/awk '{print $NF}')
opendefaultprinter

open http://127.0.0.1:631/printers
open "http://127.0.0.1:631/printers/$(/usr/bin/lpstat -d | /usr/bin/awk '{print $NF}')"


# clear print queue
function cpq() {
   /usr/bin/cancel -a -
   return 0
}


# get print job id 
lpq -P $(lpstat -d | awk '{print $NF}') | awk '{print $3}' | egrep "[[:digit:]]+"
lpstat -W not-completed | awk '{print $1}' | sed -n -E -e 's/^.*-([[:digit:]]+)$/\1/p'

# clear print queue
function cpq() {
defaultprinter=$(/usr/bin/lpstat -d | /usr/bin/awk '{print $NF}')
for jobid in $(/usr/bin/lpstat -W not-completed | awk '{print $1}' | sed -E -n -e 's/^.*-([[:digit:]]+)$/\1/p'); do
   #/usr/bin/cancel -u "$(/usr/bin/logname)" $jobid
   /usr/bin/lprm -P "$defaultprinter" $jobid
done
return 0
}


# list available fonts for man enscript
cat -n /usr/share/enscript/font.map

enscript -q -B --word-wrap -f Times-Roman25 -p - <((jot -b 'This is a test sentence!' 10 )) | pstopdf -i -o ~/Desktop/test.pdf
open ~/Desktop/test.pdf


man groff
groff --help

info groff
info --show-options groff

open http://www.groff-wiki.info
open http://www.gnu.org/software/groff/manual/groff.pdf
open /usr/share/doc/groff/1.19.1/html/momdoc/intro.html

# http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/pdfroff.1.html
open /usr/share/doc/groff/1.19.2/pdf/pdfmark.pdf


echo 'Hello, world!' | groff -Tps - | lpr

groff -Tps <((jot -b $'This is a test sentence!\n' 10)) | lpr

groff -Tps <((jot -b $'This is a test sentence!' 10)) > ~/Desktop/test.ps
open ~/Desktop/test.ps

echo 'Hello, world!' | groff -Tps - | pstopdf -i -o ~/Desktop/test.pdf
open ~/Desktop/test.pdf

groff -Tps <((jot -b $'This is a test sentence!\n' 10 )) | pstopdf -i -o ~/Desktop/test.pdf
open ~/Desktop/test.pdf


# cf. http://www.macgeekery.com/tips/cli/pretty-print_manual_pages_as_ps_pdf_or_html
function pdfman() { man $1 -t | open -f -a Preview; return 0; };
function printman() { man $1 -t | lpr; return 0; };

pdfman bash
printman bash

Reading manual pages with ManOpen

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

cd ~/Desktop
curl -LO http://www.clindberg.org/projects/ManOpen-2.5.1.dmg

hdiutil mount ~/Desktop/ManOpen-2.5.1.dmg

ls -ld /Volumes/ManOpen-2.5.1/*

/usr/bin/sudo /bin/cp /Volumes/ManOpen-2.5.1/openman /usr/bin

/usr/bin/sudo /bin/cp /Volumes/ManOpen-2.5.1/openman.1 /usr/share/man/man1

/usr/bin/sudo /bin/cp -R /Volumes/ManOpen-2.5.1/ManOpen.app /Applications

hdiutil unmount /Volumes/ManOpen-2.5.1

ls -ld /usr/bin/openman /usr/share/man/man1/openman.1 /Applications/ManOpen.app
man openman

alias om='openman'

om ls
om chflags
om openman

Testing Terminal RGB color combinations on Mac OS X

# change the background color of the current Terminal window
# for the osascript code see the comment by John Prevost at http://norman.walsh.name/2007/08/27/macProgress
# cf. also http://nslog.com/2006/11/02/terminal_color_changing_via_applescript and
# http://www.red-sweater.com/blog/220/random-color-terminal

open -a 'DigitalColor Meter'

function bgcol() { 
   declare BGCOLOR="$1"

/usr/bin/osascript <<__END__
   tell application "Terminal"
      activate
      with timeout of 10 seconds
         do script
         tell (first window whose name contains " ")
            set background color to "${BGCOLOR}"
        end tell
      end timeout
   end tell
__END__

   return 0 
}

bgcol grey
bgcol blue
bgcol white
bgcol red
bgcol orange
bgcol green
bgcol black
bgcol brown
bgcol cyan
bgcol purple
bgcol magenta


function bgcol2() { 
   declare BGCOLOR="$1"

/usr/bin/osascript <<__END__
  set RGBbg to ${BGCOLOR} as RGB color

  tell application "Terminal"
      activate
      with timeout of 10 seconds
         do script
         tell (first window whose name contains " ")
            set background color to RGBbg
        end tell
      end timeout
   end tell
__END__

  return 0 
}

bgcol2 '{57212, 56949, 40762}'
bgcol2 '{60000, 50000, 40000}'
bgcol2 '{60000, 40000, 40000}'
bgcol2 '{30810, 26728, 12934}'
bgcol2 '{24829, 27580, 33169}'
bgcol2 '{2570, 33924, 46774}'
bgcol2 '{50719, 61018, 52220}'
bgcol2 '{65123, 45636, 24237}'


function bgcol3() { 

#declare r=$[$RANDOM + 30000]     # $RANDOM generates a random integer between 0 and 32767 (cf. man bash)
#declare g=$[$RANDOM + 25000]
#declare b=$[$RANDOM + 15000]

declare nums=$(ruby -e 'ar=[]; 3.times { ar << Kernel.rand(65535) }; puts ar.join(" ")')
#declare nums=$(ruby -e 'ar=[]; n = 15_000; 3.times { ar << Kernel.rand(n) + n; n+=8000 }; puts ar.join(" ")')

declare r=$(printf "%s" "$nums" | awk '{print $1}')
declare g=$(printf "%s" "$nums" | awk '{print $2}')
declare b=$(printf "%s" "$nums" | awk '{print $3}')

printf "bgcol: ${r}, ${g}, ${b}\n"

/usr/bin/osascript <<__END__
set RGBbg to {${r}, ${g}, ${b}} as RGB color

  tell application "Terminal"
      activate
      with timeout of 10 seconds
         do script
         tell (first window whose name contains " ")
            set background color to RGBbg
        end tell
      end timeout
   end tell
__END__

  return 0 
}

for (( i=0; i<=20; i++ )); do bgcol3; sleep 3; done



# change the text color of the current Terminal window

function fgcol() { 
   declare FGCOLOR="$1"

/usr/bin/osascript <<__END__
   tell application "Terminal"
      activate
      with timeout of 10 seconds
         do script
         tell (first window whose name contains " ")
            set normal text color to "${FGCOLOR}"
        end tell
      end timeout
   end tell
__END__

   return 0 
}

fgcol grey
fgcol blue
fgcol white
fgcol red
fgcol orange
fgcol green
fgcol black
fgcol brown
fgcol cyan
fgcol purple
fgcol magenta


function defaultcolors() { 
   fgcol black
   bgcol white
   return 0 
}

defaultcolors


function fgcol2() { 

#declare r=$[$RANDOM + 30000]
#declare g=$[$RANDOM + 10000]
#declare b=$[$RANDOM]

declare nums=$(ruby -e 'ar=[]; 3.times { ar << Kernel.rand(65535) }; puts ar.join(" ")')
declare r=$(printf "%s" "$nums" | awk '{print $1}')
declare g=$(printf "%s" "$nums" | awk '{print $2}')
declare b=$(printf "%s" "$nums" | awk '{print $3}')

printf "fgcol: ${r}, ${g}, ${b}\n"

/usr/bin/osascript <<__END__
set RGBfg to {${r}, ${g}, ${b}} as RGB color

  tell application "Terminal"
      activate
      with timeout of 10 seconds
         do script
         tell (first window whose name contains " ")
            set normal text color to RGBfg
            --set bold text color to RGBfg
        end tell
      end timeout
   end tell
__END__

  return 0 
}


for (( i=0; i<=20; i++ )); do fgcol2; sleep 3; done

for (( i=0; i<=20; i++ )); do fgcol2; sleep 3; bgcol3; sleep 5; printf "\n"; done