Monday 7 October 2013

Glob expressions in Shell Scripting in Linux

1. If you are a regular user of MS Dos you might know the use of wild cards.
The same is applicable in Linux shell know as GLOB Expression

like if you write this syntax

for name in d??

this will find all the file names in your current directory with 3 characters
starting with d and then any 2 characters like doc,dol...

In the same way if we write

for name in *d??
this will show all file name ending with d following any 2 characters
just like extension name, doc,div etc.

2. a. Regular expression in enclose characters
    m[0123456789]x
    it may be any name starting with m followed by digits and ending
    with x
    this can be made short by using m[0-9]x.
  
  The same thing can be done with alphabets
   [0-9][a-z].  This expression will take anything starting with digits and ending with
   alphabets in small case. eg. 98ab but not ab98 or 98AB.

   Negation
   Condition can be negated like m[!0-9]x will take anything starting with    m, any non numeric     
  characters, ending with x,  eg. xyzABCx
  or [0-9][!a-z] will read anything starting with numbers and ending with
  anything not alphabets in small case. eg. 79XYZ.

  In case you want alphabets with both lower case and upper case then you write [a-zA-Z]
  You can also provide range of alphabets or numbers. Like [d-jF-N] will validated any string
  starting with lower case alphabets between d and j and upper case alphabets between F and N.
  The same is with  numbers. [5-9] will validate anything between 5 and 9. 234 is wrong.
 
  All this expression given above only works if files with such pattern exists otherwise it will
  return the expression itself

  Say if you write for name in [a-z]123, this will print the name of file starting with alphabets
  but ending with 123 (may be extension name), but if file with such pattern does not exists it
  will return just the expression [a-z]123.

No comments: