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

ffind - fuzzyfind from the current directory

# fuzzyfind from the current directory
function ffind() {
   declare regex filetype
   if [[ $# -gt 2 ]] || [[ $# -eq 0 ]]; then return 1; fi
   if [[ $# -eq 2 ]] && [[ "$1" == '-d' ]]; then filetype='d'; fi
   regex="$(printf "%s" "${!#}" | /usr/bin/sed -E -e 's/([^][]|\[[^][]+\])/\1\.\*/g' -e '/\.\*\$\.\*$/s/\.\*\$\.\*$/\$/')"
   regex="${PWD}/.*${regex}"
   /usr/bin/find -x "${PWD}" -type "${filetype:-f}" -iregex "$regex"
   return 0
}


ffind "searchstring"                # default is file search
ffind -d "[3-7]searchstring[5-9]"   # search for directories 
ffind "searchstring$"               # last character of file name is a "g"

str="searchstring"
str="[3-7]searchstring[5-9]"
str="search/string$"
printf "%s" "${str}" | /usr/bin/sed -E -e 's/([^][]|\[[^][]+\])/\1\.\*/g' -e '/\.\*\$\.\*$/s/\.\*\$\.\*$/\$/'

adfads

// description of your code here

File metadataDir = new File("svalka");
File screenshotsDir = new File(metadataDir, "tmpScreenshots");

Create directory and a subdirectory

// bla-bla

File metadataDir = new File("svalka");
File screenshotsDir = new File(metadataDir, "tmpScreenshots");

seticon - set icon of Mac OS X files

# See:
# http://osxutils.sourceforge.net
# http://www.sveinbjorn.org/osxutils_docs

cd ~/Desktop
curl -L -O http://surfnet.dl.sourceforge.net/sourceforge/osxutils/osxutils1.7.pkg.zip
unzip -qq osxutils1.7.pkg.zip
open -a Installer osxutils1.7.pkg

/bin/mkdir -p ~/Desktop/IconDir
/bin/cp /Library/Desktop\ Pictures/Nature{/Ladybug.jpg,'/Evening Reflections.jpg'} ~/Desktop/IconDir
/usr/bin/sips -i ~/Desktop/IconDir/*

/usr/bin/touch ~/Desktop/IconDir/testfile.txt
/bin/chmod 0777 ~/Desktop/IconDir/*

ls -l ~/Desktop/IconDir/*

open ~/Desktop/IconDir

# set icon
/usr/local/bin/seticon ~/Desktop/IconDir/Ladybug.jpg ~/Desktop/IconDir/testfile.txt

# update file system changes of open Finder window
/usr/local/bin/wsupdate ~/Desktop/IconDir/testfile.txt
#/bin/mv ~/Desktop/IconDir{/testfile.txt,/tmp.txt} && /bin/mv ~/Desktop/IconDir{/tmp.txt,/testfile.txt} 


# set icon
/usr/local/bin/seticon ~/Desktop/IconDir/'Evening Reflections'.jpg ~/Desktop/IconDir
/usr/local/bin/wsupdate ~/Desktop/IconDir

/bin/chmod -R 0755 ~/Desktop/IconDir
ls -al ~/Desktop/IconDir/*


# geticon
sips -i file.jpg
geticon -t icns file.jpg


# list files with resource forks
# cf. http://www.entropy.ch/blog/Mac+OS+X/2005/03/30/,
# http://forums.macosxhints.com/showthread.php?t=70224 and
# "can UNIX resolve OS X aliases?", http://forums.macosxhints.com/showthread.php?t=19960

cd ~/Desktop/IconDir
ls -1 | while IFS= read -r i; do if [[ -s ${i}/..namedfork/rsrc ]]; then ls -l "${i}/..namedfork/rsrc"; fi; done
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' ls -l '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' sed -n -e 'l' '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' ruby -n -e 'p $_.to_s' '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' strings '{}'/..namedfork/rsrc

# delete resource fork
find . -type f -maxdepth 1 -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -I '{}' /bin/cp /dev/null '{}/..namedfork/rsrc'

ditto --norsrc file.jpg{,.bak}
ditto --norsrc file.jpg.bak file.jpg

# some additional resource fork tools
man Rez
man DeRez
man RezWack     # create a flattened file from resource and data fork
man UnRezWack
man SplitForks
man FixupResourceForks

/Developer/Tools/Rez --help
/Developer/Tools/DeRez --help
/Developer/Tools/RezWack --help
/Developer/Tools/UnRezWack --help
/Developer/Tools/SplitForks --help
/System/Library/CoreServices/FixupResourceForks --help

ls -1 /Developer/Tools/*
/Developer/Tools/RezDet --help
/Developer/Tools/RezDet -d file; echo $?
/Developer/Tools/RezDet -s file; echo $?

man CpMac | less -N -j -9 -p 'As of Mac OS X 10.4' 
man MvMac | less -N -j -11 -p 'As of Mac OS X 10.4' 

# http://tclresource.sourceforge.net
man tclresource


Further information:

- Mac 101: Change Your Icons
- Mac OS X: Changing the Icon for a File Type
- How Do I Change File Icons And The Default Application On My Mac?
- Set Icon
- Mac Icon FAQ
- Setting an Icon From the CLI
- osxutils Documentation
- Aliases, symbolic links, Path Finder aliases... Help!
- BlueHarvest
- Making Resource-Fork-Aware Backups with rsync on Mac OS X

Counting lines

# create a test file
testfile="${HOME}/Desktop/testfile.txt"
jot -b 'sample text' 10 | cat -n > "$testfile"
printf "%s\n" >> "$testfile"                                 # add an empty line
printf "%s\n\r\n\r\n\r\r\n" "sample text" >> "$testfile"     # add lines with '\r\n' as line separators 
printf "%s" "sample text" >> "$testfile"                     # add a last line without a terminating '\n'       

open -e "$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"



# wc -l
wc -l < "$testfile"     # returns the number of '\n' characters

# ed 
ed -s "$testfile" <<< '='     # all lines

# cat
cat -n "$testfile" | awk 'END {print $1}'   # all lines


# grep
grep -c $'\n' "$testfile"                 # all lines
grep -c '^.*$' "$testfile"                # all lines
#grep -c $'\000' "$testfile"
grep -c $'\r$' "$testfile"                # all lines ending with \r\n
grep -c '^[[:space:]]*$' "$testfile"      # all blank lines
grep -cv '^[[:space:]]*$' "$testfile"     # all non-blank lines


# sed
sed -n '$=' "$testfile"                          # all lines
sed -n /$'\r'$/= "$testfile" | wc -l             # all lines ending with \r\n
sed -n '/^[[:space:]]*$/=' "$testfile" | wc -l   # all blank lines
sed -n '/[^[:space:]]/=' "$testfile" | wc -l     # all non-blank lines


# awk
awk 'END {print NR}' "$testfile"                           # all lines
awk '{x++} END {print x}' "$testfile"                      # all lines
awk '/^.*$/ {++x} END {print x}' "$testfile"               # all lines
awk '/\r$/ {++x} END {print x}' "$testfile"                # all lines ending with \r\n
awk '/^[[:space:]]*$/ {++x} END {print x}' "$testfile"     # all blank lines
awk '/[^[:space:]]/ {++x} END {print x}' "$testfile"       # all non-blank lines


# nl
nl "$testfile" | awk 'END {print $1}'
nl -b a "$testfile" | awk 'END {print $1}'   # including empty lines


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


# counting the lines of files in a directory

DIR=/path/to/dir

find "$DIR" -type f -name "*.txt" -print0 | xargs -0 wc -l

find "$DIR" -type f -name "*.txt" -print0 | xargs -0 sed -n '$='

find "$DIR" -type f -name "*.txt" -print0 | xargs -0 awk 'END {print NR}'
find "$DIR" -type f -name "*.txt" -print0 | xargs -0 awk '{x++} END {print x}'
find "$DIR" -type f -name "*.txt" -print0 | xargs -0 awk '/\r$/ {++x} END {print x}'
find "$DIR" -type f -name "*.txt" -print0 | xargs -0 awk '/^[[:space:]]*$/ {++x} END {print x}'
find "$DIR" -type f -name "*.txt" -print0 | xargs -0 awk '/[^[:space:]]/ {++x} END {print x}'


# rather slow, but without the "Argument list too long" issue: /usr/sbin/sysctl kern.argmax
# cf. http://www.onlamp.com/pub/a/bsd/2002/03/14/FreeBSD_Basics.html

declare -i linecnt=0
while read -d $'\0' file; do
   #linecnt=$((${linecnt} + $(/usr/bin/sed -n '$=' "${file}")))
   let "linecnt += $(/usr/bin/sed -n '$=' "${file}")"   # cf. help let
done < <(/usr/bin/find "$DIR" -type f -name "*.txt" -print0)

echo $linecnt

open or cd to the directory of a file path

# open directory of a file path
# can be used together with the [esc-.] key sequence
function odf() { /usr/bin/open "$(/usr/bin/dirname "$@")"; return 0; }

# cd to the directory of a file path
function cdf() { cd "$(/usr/bin/dirname "$@")"; return 0; }


ls -l /Library/Desktop\ Pictures/Nature/Tranquil\ Surface.jpg
ls -l /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/ExecutableBinaryIcon.icns 

odf [esc-.]
cdf [esc-.]


odf /System/Library/SystemProfiler/SPFirewallReporter.spreporter/Contents/Resources/
cdf /System/Library/SystemProfiler/SPFirewallReporter.spreporter/Contents/Resources/English.lproj/Localizable.strings

newfolder contextual menu item with Automator

Right-click on a folder in a Finder window and select Automator -> newfolder to create a "NewFolder".


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

current_dir="$@"
name_of_new_dir="NewFolder"

if [[ -d "${current_dir}" ]] && [[ -w "${current_dir}" ]]; then
   /bin/mkdir -p "${current_dir}${name_of_new_dir}"
fi

exit 0


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

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

open ~/Library/Workflows/Applications/Finder/newfolder.workflow

# now open your Home directory, right-click on a folder and select Automator -> newfolder to create a "NewFolder" 
open ~

dirmodes

Usage: dirmodes /path/to/directory


function dirmodes() {

   declare dir user group mods
   declare -a ar ret
   declare -i size i n 

   dir="$@"

   if [[ ! -e "$dir" ]]; then printf "%s\n" "Directory (or file) does not exist: $dir"; return 1; fi

   dir=${dir%/}      # remove a trailing slash character "/" if necessary

   OIFS="$IFS"
   export IFS=$'\n'


   i=-1
   while [[ -n "$dir" ]]; do
      i=$[i+1]
      user="$(/usr/bin/stat -f "%Su" "$dir")"
      group="$(/usr/bin/stat -f "%Sg" "$dir")"

      mods="$(/usr/bin/stat -f "%p" "$dir")"
      mods="${mods: -4}"
      #mods="$(/usr/bin/stat -f "%p" "$dir" | /usr/bin/grep -Eo "[[:digit:]]{4}$")"
  
      ar[$i]="$(printf "%-35s        %-50s\n" $user:$group:$mods $dir)"

      dir="$(/usr/bin/dirname "$dir")"

      if [[ "$dir" == '/' ]]; then 
         i=$[i+1] 
         ar[$i]="$(printf "%-35s        %-50s\n" $user:$group:$mods $dir)"
         dir=""
      fi

   done


   # get number of array elements 
   size=$(/bin/expr ${#ar[@]} - 1 )
   n=-1
   
   for (( i=$size; i>=0; i-- )); do    # reverse the array
      n=$[n+1]
      ret[$n]=${ar[$i]}
      printf "%s\n" "$(printf -- "${ar[$i]}" | tr -d '\r\n')"
   done

   export IFS="$OIFS"

   return 0

}

Compressing a directory with rar on Linux

I've been struggling to get this to work for so long that when I finally got it going I had to throw it up here so I wouldn't lose it.
rar a -m5 -R output.rar /etc/

This will create a max compression (not taking into account dictionary sizes and the like) archive of the entire etc directory.

Latest file to download

Perl script using shell command to get(/grep) the lastest file on directory for download.

Just Create .htaccess (DirectoryIndex .latest.cgi) for more automations, so to get the latest files, just point your download link to: "yoursite.com/files/"

#!/usr/bin/perl
#This is .latest.cgi
$|++; my @file = `ls -1 -t -p | grep -v -P '/'`; 
print "Location: $file[0]\n\n";
exit;