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

Limit Google searches by date

See: Easy Way to Find Recent Web Pages

date='d15'
date='m3'
date='y'
words='unix linux shell bash'
site='codesnippets.joyent.com'

open -a Safari "http://www.google.com/search?q=${words// /+}&as_qdr=${date}"

open -a Safari "http://www.google.com/search?q=site%3A${site}%20${words// /+}&as_qdr=${date}"


# sbd - search by date
# cf. also http://codesnippets.joyent.com/posts/show/1700

function sbd() {
   declare date site words
   date="${1}"
   words="${2}"
   site="${3}"
   if [[ $# -eq 2 ]]; then
      /usr/bin/open -a Safari "http://www.google.com/search?q=${words// /+}&as_qdr=${date}"
   elif [[ $# -eq 3 ]]; then
      /usr/bin/open -a Safari "http://www.google.com/search?q=site%3A${site}%20${words// /+}&as_qdr=${date}"
   else
      return 1
   fi
   return 0
}


sbd d 'unix linux shell bash'
sbd m5 'unix linux shell bash'
sbd y3 'unix linux shell bash' codesnippets.joyent.com

Watch YouTube videos with QuickTime

Requires SIMBL and GreaseKit. Tested on Safari.
# YouTube in MP4 via QuickTime Plugin!
# http://www.joeyhagedorn.com/2008/04/16/youtube-in-mp4-via-quicktime-plugin

open -a Safari http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js


# Download YouTube Videos as MP4 Files
# http://googlesystem.blogspot.com/2008/04/download-youtube-videos-as-mp4-files.html

open -a Safari http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js


1. Youtube QT (http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js)
// ==UserScript==
// @name           Youtube QT
// @namespace      userscripts.org
// @description    Plays the high-resolution YouTube video in an embedded Quicktime player 
// @version        0.1
// @include        http://youtube.com/watch?*
// @include        http://www.youtube.com/watch?*
// @include        http://*.youtube.com/watch?*
// ==/UserScript==
	
var video_id = null;
var video_hash = null;
var video_player = document.getElementById('movie_player');

if (video_player) {var flash_variables=video_player.attributes.getNamedItem('flashvars');
	if (flash_variables) {var flash_values=flash_variables.value;
		if (flash_values) {var video_id_match=flash_values.match(/video_id=([^(\&|$)]*)/);
			if (video_id_match!=null) video_id=video_id_match[1];
				var video_hash_match=flash_values.match(/t=([^(\&|$)]*)/);
				if (video_hash_match!=null) video_hash=video_hash_match[1];
		}
	}
}

if (video_id==null || video_hash==null) {var args=unsafeWindow.swfArgs;
	if (args) {video_id=args['video_id'];
		video_hash=args['t'];
	}
}

if (video_id==null || video_hash==null) return;

var yt_mp4_path = 'http://www.youtube.com/get_video?fmt=18&video_id='+video_id+'&t='+video_hash;
var div_embed=document.getElementById('watch-player-div');

if (div_embed) {div_embed.innerHTML='<embed src=\''+yt_mp4_path+'\' type="video/mp4" width=480 height=400 scale=\'aspect\'></embed>';
};


2. Download YouTube Videos as MP4 (http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js)
// ==UserScript==
// @name           Download YouTube Videos as MP4
// @description    Adds an option to download YouTube videos.
// @namespace      http://googlesystem.blogspot.com
// @include        http://*.youtube.com/watch?*
// @include        http://youtube.com/watch?*
// @version        0.4
// ==/UserScript==

if ( navigator.userAgent.indexOf("AppleWebKit") != -1 ) {
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = window.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }

} else {
    (function () {
    
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = unsafeWindow.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }
      
    })();
}

Compile & install git on Mac OS X

Requires Xcode.

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


# see what you already have
which asciidoc gpg gettext git
find /usr/lib /usr/local/lib -iname "*expat*"
python -V   # should be Python 2.4 or newer


# rudix
# http://rudix.org

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/rudix/rudix-1.5.2-0.dmg
hdiutil mount ~/Desktop/rudix-1.5.2-0.dmg
ls -1 /Volumes/* | egrep -i rudix
open -a Installer /Volumes/rudix/rudix.pkg
hdiutil unmount /Volumes/rudix

which rudix
man rudix


# expat
# also available via http://rudix.org

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/expat/expat-2.0.1.tar.gz
tar -xvzf expat-2.0.1.tar.gz 
cd expat-2.0.1
./configure --prefix=/usr/local
make
make check
sudo make install

find /usr/local -iname "*expat*"


# Python 2.5.2

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/rudix/python-2.5.2-1.dmg
hdiutil mount ~/Desktop/python-2.5.2-1.dmg
sudo rudix -i /Volumes/python/python.pkg
hdiutil unmount /Volumes/python

which python
python -V     # Python 2.5.2


# python-docs

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/rudix/python-docs-2.5.2-1.dmg
hdiutil mount ~/Desktop/python-docs-2.5.2-1.dmg
sudo rudix -i /Volumes/python-docs/python-docs.pkg
hdiutil unmount /Volumes/python-docs

man /usr/local/share/man/man1/python.1
ls -1 /usr/local/share/doc/python/*
find /usr/local/share/doc/python -mindepth 1 -maxdepth 1
find /usr/local/share/doc/python/doc -mindepth 1 -maxdepth 1
find /usr/local/share/doc/python/mac -mindepth 1 -maxdepth 1


# asciidoc
# asciidoc 8.3.0 requires Python 2.4 or newer

cd ~/Desktop
curl -L -O http://www.methods.co.nz/asciidoc/asciidoc-8.3.0.tar.gz
tar -xvzf asciidoc-8.3.0.tar.gz
cd asciidoc-8.3.0
open -e ~/Desktop/asciidoc-8.3.0/INSTALL
sudo ./install.sh

which asciidoc
man asciidoc


# GPG

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/rudix/gnupg-1.4.9-2.dmg
hdiutil mount ~/Desktop/gnupg-1.4.9-2.dmg
sudo rudix -i /Volumes/gnupg/gnupg.pkg
hdiutil unmount /Volumes/gnupg

which gpg
gpg --version
man gpg



# GetText

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/rudix/gettext-0.17-1.dmg
hdiutil mount ~/Desktop/gettext-0.17-1.dmg
sudo rudix -i /Volumes/gettext/gettext.pkg
hdiutil unmount /Volumes/gettext

which gettext
gettext --version
man gettext
open /usr/local/share/locale




# git 
# http://rudix.org

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/rudix/git-1.5.6.2-1.dmg
hdiutil mount ~/Desktop/git-1.5.6.2-1.dmg
sudo rudix -i /Volumes/git/git.pkg
hdiutil unmount /Volumes/git

which git
git --version
man git

sudo rudix -r git.pkg



# git
# http://git.or.cz

cd ~/Desktop
curl -L -O http://kernel.org/pub/software/scm/git/git-1.6.0.4.tar.gz
tar -xzf git-1.6.0.4.tar.gz
cd git-1.6.0.4
./configure
make
sudo make install

which git
git --version


# git man pages

cd ~/Desktop
curl -L -O http://kernel.org/pub/software/scm/git/git-manpages-1.6.0.4.tar.gz
sudo tar -C /usr/local/share/man -xzf git-manpages-1.6.0.4.tar.gz


git --help

git help add
git help bisect
git help shell
git help git-svn
git help git-daemon

git help gittutorial
git help gitcore-tutorial
git help gitglossary


cd ~/Desktop
mkdir -p ~/Desktop/git-test
cd ~/Desktop/git-test
openport 9418   # cf. http://codesnippets.joyent.com/posts/show/1747
git clone git://git.kernel.org/pub/scm/git/git.git
closeport 9418
open ~/Desktop/git-test
find ~/Desktop/git-test/git -mindepth 1 -maxdepth 1 -ls


# To configure git see:
# - http://dysinger.net/2007/12/30/installing-git-on-mac-os-x-105-leopard/
# - http://arthurkoziel.com/2008/05/02/git-configuration/
# - http://www.bergek.com/wp-content/uploads/2008/09/git-install.sh
# - http://git.or.cz/gitwiki/GitTips


References:

- Git - Fast Version Control System
- Wikipedia: Git
- Rudix
- Install git on Mac OS X 10.4 (expat, asciidoc)
- Installing GIT on Mac OS X 10.5 Leopard (GPG, GetText)
- Compiling Git and git-svn on OSX Tiger (git-svn, Perl)
- Getting git-svn working on the Mac
- Git vs. Mac HFS+ filesystem (UFS & git)
- git-osx-installer
- Git Configuration (on Mac OS X)
- GitTips
- Git User's Manual
- Tag: git
- Git Quick Reference
- Git Guide
- Git Internals: Source code control and beyond
- PeepCode Git screencast
- git hosting with Leopard
- Hosting Git repositories, The Easy (and Secure) Way
- The Git Community Book
- Setting up Git on OSX
- Git and Binaries
- Git cheat sheet
- Setting up a new remote git repository
- Sharing git repositories via OS X's built-in web sharing
- GitHub Tips: Removing a Remote Branch
- Using git in the Finder
- GitX - a git GUI for Mac OS X

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/\.\*\$\.\*$/\$/'

Delete specified files in the current directory

man find | less -p '-delete'

find . -mindepth 1 -maxdepth 1 -type f -name '*.txt' -ls

find . -mindepth 1 -maxdepth 1 -type f -name '*.txt' -delete

sudo shell

# cf. http://nevali.net/2006/04/sudo-and-su/
#function sudosh() { /usr/bin/sudo -H -i; return 0; }
alias sudosh='/usr/bin/sudo -H -i'

Test ownership of launchd processes

The following launchd item will execute a simple script every 20 seconds to test or show the ownership of the processes executed by the script. In addition, the script will print out the names and values of its shell environment variables.

To set up the launchd item log in to an admin user account. Use at your own risk.

# LAUNCHD ITEM

/usr/bin/sudo /bin/bash -c '

yourname=$(/usr/bin/logname)
LaunchdPlistFile="/Library/LaunchDaemons/user.${yourname}.launchd.test.plist"
EX_MARK='!'

/bin/cat > "${LaunchdPlistFile}" <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<${EX_MARK}DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Disabled</key>
        <true/>
        <key>Debug</key>
        <true/>


        <key>UserName</key>
        <string>${yourname}</string>
        <key>GroupName</key>
        <string>${yourname}</string>


        <key>EnvironmentVariables</key>
        <dict>
                <key>PATH</key>
                <string>/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin</string>
                <key>YetAnotherEnvironmentVar</key>
                <string>/path/to/dir</string>
        </dict>
        <key>Label</key>
        <string>user.${yourname}.launchd.test</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Users/${yourname}/Desktop/launchd_test.sh</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceDescription</key>
        <string>Test ownership of launchd processes</string>
        <key>StandardErrorPath</key>
        <string>/Users/${yourname}/Desktop/launchd_test_error.log</string>
        <key>StandardOutPath</key>
        <string>/Users/${yourname}/Desktop/launchd_test.log</string>
        <key>StartInterval</key>
        <integer>20</integer>
        <key>Umask</key>
        <integer>002</integer>
</dict>
</plist>
EOF
'



: <<-'COMMENT'

# switch UserName & GroupName

        <key>UserName</key>
        <string>${yourname}</string>
        <key>GroupName</key>
        <string>${yourname}</string>
or
        <key>UserName</key>
        <string>root</string>
        <key>GroupName</key>
        <string>wheel</string>

or ...

COMMENT


yourname=$(/usr/bin/logname)

LaunchdPlistFile="/Library/LaunchDaemons/user.${yourname}.launchd.test.plist"

open -e "${LaunchdPlistFile}"


# SCRIPT

LaunchdTestScript="/Users/${yourname}/Desktop/launchd_test.sh"

/bin/cat > "${LaunchdTestScript}" <<-'EOF'
#!/bin/bash
# /bin/sh

# cf. man 5 launchd.plist | less -p 'A daemon or agent launched by launchd SHOULD:'
trap '/usr/bin/logger -i "received SIGTERM for launchd test"; exit 1' TERM

# write stdout & stderr to console.log in /Library/Logs/Console/
# open -a Console
# (requires /bin/bash to work correctly!)
#exec >/dev/console 2>&1

echo
echo "SYSTEM LOGS:"
/usr/bin/logger -i "logger:  $0"
/usr/bin/syslog -s -l 1 "syslog:  $0"
echo

echo
echo 'id:'
echo
/usr/bin/id | /usr/bin/sed -E \
   -e $'s/,? /\\\n/g' \
   -e $'/groups=/s/groups=/groups:\\\n/' \
   -e 's/=/ = /g' \
   -e $'s/[()]/   /g'
echo

# cf. man mail | less -p HOME
# cf. Read local Unix mail in Mail.app, http://codesnippets.joyent.com/posts/show/1392
#export HOME=/Users/$(/usr/bin/whoami)
#echo "hello world $(date)" | /usr/bin/mail -s 'test mail' $(/usr/bin/whoami)@localhost

echo
echo "SHELL: $SHELL"
echo "BASH: $BASH"
echo
echo "current set of shell flags: $-"    # cf. help set
echo
echo "SHELLOPTS: $SHELLOPTS"
echo
echo 'set:'
echo
set
echo
printf "%q  %q\n" "IFS:" "$IFS"
echo
echo 'env:'
echo
/usr/bin/env
echo
echo
echo 'shopt ... on:'
echo
shopt | /usr/bin/egrep 'on$'
#set -o | /usr/bin/egrep 'on$'
echo


cd ~
echo "HOME: $PWD"
echo
echo 'try to cd to /private/var/launchd/0'
cd /private/var/launchd/0
return_code=$?
echo "cd exit status: ${return_code}"
echo
if [[ ${return_code} -eq 0 ]]; then echo "ROOT PRIVILEGES"; else echo "NO ROOT PRIVILEGES"; fi
echo

echo "PPID:  $PPID"
echo
echo "PID:  $$"
echo

echo 'ps -p PID:'
echo
/bin/ps -p $PPID
echo
/bin/ps -p $$
echo
echo 'lsof -p PID:'
echo
/usr/sbin/lsof -p $PPID 2>/dev/null
echo
/usr/sbin/lsof -p $$ 2>/dev/null
echo

echo "users:  $(/usr/bin/users)"
echo
echo "groups:  $(/usr/bin/groups)"    # /usr/bin/id -Gn
echo
echo "logname:  $(/usr/bin/logname)"
echo
echo "whoami:  $(/usr/bin/whoami)"   # /usr/bin/id -un


echo; echo
echo "#----------------------------------------------------------------------------------------------- $(date)"
echo; echo

exit 0
#exit 1

EOF



open -e "${LaunchdPlistFile}"
open -e "${LaunchdTestScript}"

/usr/bin/sudo /usr/sbin/chown root:wheel "${LaunchdPlistFile}"
/usr/bin/sudo /bin/chmod 0644 "${LaunchdPlistFile}"

/usr/sbin/chown ${yourname}:${yourname} "${LaunchdTestScript}"
/bin/chmod u+x "${LaunchdTestScript}"

ls -l "${LaunchdPlistFile}"
ls -l "${LaunchdTestScript}"


# enable launchd item
/usr/bin/sudo /bin/launchctl load -w "${LaunchdPlistFile}" 2>/dev/null

# disable launchd item
/usr/bin/sudo /bin/launchctl unload -w "${LaunchdPlistFile}" 2>/dev/null

ls -l /Users/${yourname}/Desktop/launchd_test.log
ls -l /Users/${yourname}/Desktop/launchd_test_error.log

open -a Console /Users/${yourname}/Desktop/launchd_test.log
#/usr/bin/srm -v /Users/${yourname}/Desktop/launchd_test.log

open -a Console /Users/${yourname}/Desktop/launchd_test_error.log


/usr/bin/sudo /bin/launchctl list
/usr/bin/sudo /usr/bin/fs_usage  | /usr/bin/egrep -i launchd_test


# convert possible tabs to spaces
#/usr/bin/expand "${LaunchdPlistFile}" > ~/Desktop/user.${yourname}.launchd.test.plist
#open -e ~/Desktop/user.${yourname}.launchd.test.plist


man 8 launchd
man 5 launchd.plist
man 5 launchd.conf
man 1 launchctl


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


# set launchd log level to debug
# cf. http://www.puredarwin.org/developers/booting/launchd
# sudo launchctl log level debug
sudo bash -c 'echo "log level debug" >> /private/etc/launchd.conf'
echo 'log level debug' >> ${HOME}/.launchd.conf

sudo nano /private/etc/launchd.conf
ls -l /private/etc/launchd.conf


# send all launchd logging output to /private/var/log/launchd.log
# cf. http://developer.apple.com/technotes/tn2004/tn2124.html#SECLAUNCHDLOGGING
sudo cp -ip /etc/syslog.conf /etc/syslog.conf-orig
(cat /etc/syslog.conf-orig ; echo "launchd.* /var/log/launchd.log" ) | sudo cp /dev/stdin /etc/syslog.conf
sudo kill -HUP `cat /var/run/syslog.pid`

ls -1 /private/var/log/*log
ls -l /private/var/log/launchd.log

open -a Console /private/var/log/launchd.log


Further information on launchd:

- Getting started with launchd
- AFP548: launchd in Depth
- Wikipedia: launchd
- Mac OS Forge: launchd
- PureDarwin: launchd
- Mac OS X Debugging Magic: launchd
- Daemons and Agents
- Daemons and Agents: Execution Contexts
- Daemons and Agents: Hints and Tips
- Mac OS X Server 10.5: Setting a custom umask
- launchd gotcha
- Re: how to run scripts at shutdown - how does launchd shutdown a system?
- Starting PostgreSQL 8.3 through launchd on Mac OS X 10.5.1 Leopard
- The Future of Init, Part IIb: OS X Launchd

iregex

function iregex() {
   declare escaped_str iregexstr lower upper
   escaped_str="$(printf "%q" "${1}")"
   iregexstr=
   lower="$(printf "%s" "${escaped_str}" | /usr/bin/tr '[[:upper:]]' '[[:lower:]]')"
   upper="$(printf "%s" "${escaped_str}" | /usr/bin/tr '[[:lower:]]' '[[:upper:]]')"

   for ((i=0; i < "${#lower}"; i++)); do
      iregexstr="${iregexstr}[${lower:${i}:1}${upper:${i}:1}]"
   done

   printf "%s" "${iregexstr}" | /usr/bin/sed -E -e 's/\[([[:space:]])[[:space:]]\]/\1/g'  -e 's/\[([[:punct:]])[[:punct:]]\]/\1/g'
   return 0
}


iregex 'hello \ | / again!?'
re="$(iregex 'hello \ | / again!?')"


# replace the following string
string='helLo \ | / again!?'

re_str='hello \ | / again!?'
iregex "${re_str}"
regex="$(iregex "${re_str}")"   # always use iregex "${re_str}"
echo "${regex}"

echo "${string}" | sed "s/${regex}/replacement worked/g"   # / not escaped in regex
echo "${string}" | sed "s|${regex}|replacement worked|g"   # always use "s|${re}|replacement|"


# note: printf does not escape / to \/ in function iregex above
#printf "%q\n" "/|\ "
printf "%q\n" '/|\'   


# cf. gnused, http://codesnippets.joyent.com/posts/show/1835
string='helLo \ | / again!?'
echo "${string}" | gnused 's/hello \\ | \/ again!?/replacement worked/ig'
echo "${string}" | gnused 's|hello \\ \| / again!?|replacement worked|ig'


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


# replace the following string containing a tab character \t
string=$'helLo \ | / \tagain!?'
echo "${string}"
iregex "${string}"


re_str1='hello \ | / '
re_str2=$'\t'
re_str3='again!?'

re1="$(iregex "${re_str1}")"
re2="${re_str2}"
re3="$(iregex "${re_str3}")"

echo "${string}" | sed "s|${re1}${re2}${re3}|replacement worked|g"

echo "${string}" | gnused 's|hello \\ \| / \tagain!?|replacement worked|ig'


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


TAB=$'\t'

echo $'abc\tdef'
echo $'abc\tdef' | sed $'s/\t//'
echo $'abc\tdef' | sed s/$'\t'//
echo $'abc\tdef' | sed "s/${TAB}//"

echo $'abc\tdef' | sed $'s/\t/TAB/'
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed $'s/TAB/\t/'
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed s/TAB/$'\t'/
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed "s/TAB/${TAB}/"


# gnused

echo $'abc\tdef' | sed 's/\t/TAB/'
echo $'abc\tdef' | gnused 's/\t/TAB/'

echo $'abc\tdef' | gnused $'s/\t/TAB/'
echo $'abc\tdef' | gnused "s/${TAB}/TAB/"


echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused $'s/TAB/\t/'
echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused s/TAB/$'\t'/
echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused "s/TAB/${TAB}/"

echo $'abc\tdef' | gnused 's/\t/TAB/' | gnused 's/TAB/\t/'

Debugging a file name with a backslash character in Bash

# create a file name containing a backslash character \
file=${HOME}/Desktop/'te:st\file'.txt
echo "${file}"
echo "${file}" | sed -n -e 'l'

echo 'This is a test case for a file name containing a backslash \ character!' > "${file}"
open -e "${file}"

set -vx

# note: avoid trailing spaces in ed commands
cat <<EOF | /bin/ed -s "${file}"
H
,g|^This|s|test case|SUCCESSFUL TEST CASE|
w
EOF

open -e "${file}"


# escape backslashes
cat <<EOF | /bin/ed -s "${file//\\/\\\\}"
H
,g|^This|s|test case|SUCCESSFUL TEST CASE|
w
EOF

open -e "${file}"


# printf "%q"
help printf | sed -E "s/(%q)/$(printf '\e[1m\\1\e[m')/"
echo "${file}"
echo "$(printf "%q" "${file}")"   # cf. help printf
echo "$(printf "%q" "${file}")" | sed -n -e 'l'

# escape file name
cat <<EOF | /bin/ed -s "$(printf "%q" "${file}")"
H
,g|^This|s|backslash|BACKSLASH|
w
EOF

open -e "${file}"


echo "${file}"
echo "${file}" | sed -n -e 'l'

file="${file//\\/\\\\}"
echo "${file}"
echo "