Wednesday, July 18, 2012
4:23 AM

Bash Script: Using Globbing (glob) in bash script


Glob characters
* - means 'match any number of characters'. '/' is not matched
? - means 'match any single character'
[abc] - match any of the characters listed. This syntax also supports ranges, like [0-9]

Below is a simple script which explains the problem and also provide the solution using globbing:

Source:
cat glob.sh
#!/bin/bash

echo "Creating 2 files with space: this is first file.glob and another file with name.glob "
`touch "this is first file.glob"`
`touch "another file with name.glob"`

echo "---------------------------------"
echo "Using for loop to search and delete file ... failed :( "
for file in `ls *.glob`; do
        echo $file
        `rm $file`
done

echo "-------------------------------"
echo
echo "Using the another for loop to search for the same set of files ... but failed :("
for filename in "$(ls *.glob)"; do
        echo $filename
        `rm $filename`
done

# This is the example of using glob in the script
# This time BASH does know that it's dealing with filenames
echo "-------------------------------"
echo "Finnaly able to delete the file using glob method. :)"
for filename in *.glob; do
        echo "$filename"
        `rm "$filename"`
done


Continue Reading...

0 comments:

Post a Comment