Matching File Names with glob

The glob command expands a pattern into the set of matching file names. The general form of the glob command is:

glob ?flags? pattern ?pattern? ...

The pattern syntax is similar to the string match patterns:

  • * matches zero or more characters.

  • ? matches a single character.

  • [abc] matches a set of characters.

  • {a,b,c} matches any of a, b, or c.

  • All other characters must match themselves.

The -nocomplain flag causes glob to return an empty list if no files match the pattern. Otherwise, glob raises an error if no files match.

The -- flag must be used if the pattern begins with a -.

Unlike the glob matching in csh, the Tcl glob command matches only the names of existing files. In csh, the {a,b} construct can match nonexistent names. In addition, the results of glob are not sorted. Use the lsort command to sort its result if you find it important.

Example 9-11 shows the FindFile procedure, which traverses the file system hierarchy using recursion. At each iteration it saves its current directory and then attempts to change to the next subdirectory. A catch guards against bogus names. The glob command matches file names:

Example 9-11 Finding a file by name.
proc FindFile { startDir namePat } {
   set pwd [pwd]
   if [catch {cd $startDir}err] {
      puts stderr $err
      return
   }
   foreach match [glob -nocomplain -- $namePat]{
      puts stdout [file join $startDir $match]
   }
   foreach file [glob -nocomplain *] {
      if [file isdirectory $file] {
         FindFile [file join $startDir $file] $namePat
      }
   }
   cd $pwd
}

Expanding Tilde in File Names

The glob command also expands a leading tilde (~) in filenames. There are two cases:

  • ~/ expands to the current user's home directory.

  • ~user expands to the home directory of user.

If you have a file that starts with a literal tilde, you can avoid the tilde expansion by adding a leading ./ (e.g., ./~foobar).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.213.49