Dr. Mark Humphrys

School of Computing. Dublin City University.

Home      Blog      Teaching      Research      Contact

Search:

CA249      CA318      CA425      CA651

w2mind.computing.dcu.ie      w2mind.org


Shell utilities



grep

grep                    search for a string

grep string file

(output of prog) | grep string | grep otherstring

-i    ignore case
-v    return all lines that do NOT match




string matching / regular expressions

^                       start-of-line
$                       end-of-line
.                       any character

where "c" stands for the character:

c*			0 or more instances of c
cc*			1 or more instances of c
grep "  *"		1 or more spaces
.*                  any sequence of characters

where "c" has a special meaning, e.g. is $ or ., etc:

\c                  the character itself
grep "\."           the '.' character itself




cut, sed

cut     extract columns of text on command-line

e.g. To extract the RHS columns of the ls listing (by character or by field):

  ls -l | cut -c28-

  ls -l | cut -f6- -d' '



sed     substitute text on the command-line

sed 's|oldstring|newstring'     change first match on each line
sed 's|oldstring|newstring|g'   change all matches 

e.g. To do an ls that highlights the HTML files:

 ls -l | sed 's|\.html|  [Hypertext HTML file]|g'

sed takes a single string (enclosed in quotes) as an argument.
The '|' inside the string above are used just as separators.
We can actually use any character.


sed examples



tr, awk


tr    - character substitutions

change spaces to new lines:

cat file | tr ' ' '\n' 


awk - a powerful pattern scanning and processing language


dirname, basename

useful cutting and pasting with filenames
dirname	  

basename	  

$ echo $home /users/group/me $ dirname $home /users/group $ basename $home me $ dirname `dirname $home` /users




date

date                         looks like: "Tue Feb 17 16:28:33 GMT 2009"
CURRENTDATE=`date`           remember backquotes
echo $CURRENTDATE             

date "+%b %e"                looks like: "Jan 21" (see "man date")
CURRENTDATE=`date "+%b %e"`    
echo $CURRENTDATE             

e.g.
  1. We want a random temporary filename:
    filename="/tmp/random.`date +%H%M%S`.txt"
    
    Perhaps not random enough. e.g. 2 clients accessing server at same second. A totally unique, random temporary name can be got from   $$   which is the process ID of this invocation of the shell script:
    filename=/tmp/random.$$.txt
    

  2. Or want a different seed each time for random-number generator.

On bash (but not csh), see also the following strange environment variable. It does not exist until you try to access it. Then it exists!
set | grep -i random
echo $RANDOM  
set | grep -i random
echo $RANDOM            
echo $RANDOM            


Feeds      HumphrysFamilyTree.com

Bookmark and Share           On Internet since 1987.