21 January 2012

Pattern Matching with Wild-cards in Linux

Leave a Comment


Wild-Cards in Linux  (Globbing patterns)


                        Wild-card are shell feature which make command line more powerful than GUI file manager. They are also known as globbing patterns. They are used by various command-line utilities to work with multiple files. Various wild-cards are:

1. * : none or any number of characters.

$ ls file*                       list all files which starts with file


$ touch file1 file2 file3
$ ls file*
file1 file2 file3

*touch is use to create empty file/s.




$ ls *file*                     list all files which contains file in their name


$ touch  1_file_my  2_file_your  3_file_others
$ ls *file*
1_file_my   2_file_your   3_file_others  file1  file2  file3



$ ls *.lst                       list all files which end with .lst


$ ls *.lst
abc.lst   def.lst    pqr.lst    sandeep2.lst    sandeep.lst     xyz.lst

* echo *  list all files in current directory.


2. ?  : Match single character only.

$ ls file?                      list all files which has single character after  file



$ touch file1 file2 file3
$ ls file?
file1 file2 file3




$ ls ?file?         list all files which has single character before and after file in their name


$ touch  1file1  2file2  3file3
$ ls ?file?
1file1  2file2  3file3



$ ls ??    List all those files and the content of the directory which has two character long name.


$ mkdir cs
$ cd cs
$ pwd
/home/sandeep/cs

$ touch file1 file2 file3
$ cd
$ pwd
/home/sandeep

$ touch f1 f2 f3
$ ls ??
f1  f2  f3


cs:
file1  file2  file3


js:
index.html  jquery


* There are two things that * and ? can't match . First they don't match a file-name beginning with a dot(.) , but they can match any number of dots between the words. Second these character does not match the / in a path name. 


$ touch .file1 .file2 .file3
$ ls *file
ls: cannot access *file: No such file or directory

$ ls .file*
.file1 .file2 .file3

$ touch file1.1 file2.2 file3.3
$ ls file*
file1 file1.1 file2 file2.2 file3 file3.3


3. [abc] : Match a single character - either a , b or c.

$ touch file1 file2 file3 file4
$ ls file[1234]
file1 file2 file3 file4



4. [a-c] : Match a single character that is within ASCII range of the characters a and c.


$ touch file1 file2 file3 file4
$ ls file[1-4]
file1 file2 file3 file4



5. [!abc] :  Match a single character that is not an a , b or c.

$ touch file1 file2 file3 file4
$ ls file[!12]
file3 file4



6. [!a-c] :   Match a single character that is not within ASCII range of the characters a and c.

$ touch file1 file2 file3 file4 file5 file6 file7
$ ls file[!1-5]
file6 file7



7. {pat1,pat2} : Match totally dissimilar patterns.

$ touch  file1.lst  file1.txt   file1.doc
$ ls *.{lst,doc,txt}
file1.doc  file1.txt   file1.lst

If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

0 comments:

Post a Comment