Linux basics from the founder of Gentoo. Part 1 (4/4): Glob Substitutions

Original author: Daniel Robbins, Chris Houser, Aron Griffis
  • Transfer
  • Tutorial
The final part of the translation of the first part of a wonderful series of study guides. Previous excerpts from the links: beginning , second and third .

In this fourth passage, the use of wild cards * , [] and ? to substitute paths by pattern. And also, the results of the first part are summed up. Enjoy! ;)

The use of jokers


Meet the Jokers


In everyday use, Linux often happens when you need to perform a single operation (for example rm) on many filesystem objects at a time. In such situations, entering many files into the command line is often quite burdensome:



$ rm file1 file2 file3 file4 file5 file6 file7 file8

To solve this problem, you can benefit from the built-in Linux jokers support. This support is also called “globbing” (for historical reasons; also known in Russian as “universal file names” - approx. Per.), It allows you to specify many files at a time using the wild concatenation pattern. Bash and other Linux teams interpret this pattern by looking at the drive for files that suit it. So, if you have files file1 to file8 in the current working directory, you can delete them by typing:



$ rm file[1-8]

Or if you just want to delete all files with names starting with file , including the file itself named file , you can type:



$ rm file*

Wild concatenation "*" matches any character or set of characters, or even their absence. Of course, glob jokers can be used for much more than just deleting files, as we will see later.



Inappropriate templates


If you need to list all the filesystem objects in / etc starting with "g", as well as g itself , then you can enter:



$ ls -d /etc/g*
/etc/gconf /etc/ggi /etc/gimp /etc/gnome /etc/gnome-vfs-mime-magic /etc/gpm /etc/group /etc/group-

And now about what will happen if you specify a template that does not fit any file system object. In the following example, we tried to iterate over all the files in / usr / bin that start with “asdf” and end with “jkl”, potentially including asdfjkl :



$ ls -d /usr/bin/asdf*jkl
ls: /usr/bin/asdf*jkl: No such file or directory


Here is what will happen. Usually, when we specify a template, and if one or more files are placed in it in the implied file system, then bash replaces our template with a space-separated list of all suitable objects. However, when there are no matches with the template, bash leaves the passed argument with the jokers as it is. So, then ls cannot find the file / usr / bin / asdf * jkl and gives us an error. The basic rule here is this: glob-templates are deployed only if they coincide with the objects of the file system. Otherwise, they remain untouched and are literally transferred to the program call.



Joker syntax: * and?


So, we already saw how globbing works, but now it’s worth considering the syntax of jokers. Special symbols are used as jokers:



* - matches zero or more characters. This means: "there can be anything, including nothing." Examples:


  • / etc / g * matches all files in / etc starting with g and the g file itself ;
  • / tmp / my * 1 matches all files in / tmp that begin with my and end with 1, including the file my1.

? - equal to any one character. Examples:


  • myfile? matches any file whose name is myfile and any one character following it;
  • / tmp / notes? txt will match, for example, with /tmp/notes.txt and / tmp / notes_txt if they exist.

Joker Syntax: []


Does this joker look like ? but more accurate. To use it, put any characters you need inside [] . The resulting expression will satisfy any one of these characters. You can also use "-" to indicate a range, and even a combination of ranges. Examples:


  • myfile [12] will match myfile1 and myfile2 . The joker will work if at least one of these files exists in the current directory;
  • [Cc] hange [Ll] og will match Changelog , ChangeLog , changeLog and changelog . As you can see, the use of bracket jokers is very convenient for indicating options with capital letters;
  • ls / etc / [0-9] * will show all files in / etc starting with a decimal digit;
  • ls / tmp / [A-Za-z] * displays all files in / tmp that start with a capital or small Latin letter.

The construction [!] Is equivalent to the construction [], except that instead of matching the characters inside the brackets, it matches any character that is NOT listed between [! and]. Example:


  • rm myfile [! 9] will delete all files named myfile plus one character except myfile9 .

Joker Cautions


Now a few warnings to be careful when using jokers. Since bash handles wildcard characters (?, [,] And *) in a special way, you need to take special care when you write an argument for a command containing these characters. For example, if you want to create a file containing the string "[fo] *", then the following command may not give the desired result:



$ echo [fo]* > /tmp/mynewfile.txt

If the template [fo] * matches any files in the current working directory, then you will find their names inside /tmp/mynewfile.txt , instead of the expected [fo] *. Decision? Well, one of them will enclose your characters in single quotes, which will tell bash not to do any expansion of the jokers in them:



$ echo '[fo]*' > /tmp/mynewfile.txt

Using this approach, your new file will contain [fo] * literally, as intended. Also, you can use the escape backslash to tell bash that [,] and * should be interpreted literally, and not like jokers:



$ echo \[fo\]\* > /tmp/mynewfile.txt

Both approaches (single quotes and escaping backslashes) work with the same effect. Since we are talking about handling backslashes, it would be nice to clarify now that in case you want to specify \ literally, you can either take it in single quotes or type \\ (this will be converted to \).



Note:


Double quotes work just like single quotes, but still allow bash to do some limited processing. Therefore, single quotation marks are your best bet if you are really interested in literally passing text to the command. You can get more information about opening jokers by typing man 7 glob. For more information about quotes in bash, type man 1 bash and read the section called QUOTING. If your plans include passing LPI exams, then consider this as your homework. =)



Summary and links to other resources


Total


Congratulations; You've reached the end of our Linux basics review! I hope this helps you strengthen your basic knowledge of Linux. The topics you learned here, including bash basics, basic Linux commands, links, and jokers, laid the foundation for our next tutorial on the basics of administration, in which we look at topics such as regular expressions, ownership and access rights, and user account management , and much more.



By continuing to dive into these tutorials, you will soon achieve the LPIC Level 1 certification from the Linux Professional Institute. Speaking of this certification, if this is really what you are interested in, we recommend that you study the resources in the paragraph below, which have been carefully selected for the material covered in this guide.



References


In the “Bash with Examples” series of articles, Daniel shows how to use bash software constructs to write your own bash scripts. This series (mainly 1 and 2 parts) will be an excellent preparation for LPIC Level 1:


  • Bash in the examples, Part 1: Fundamentals of programming in the Bourne-again shell - in English , translation into Russian is expected
  • Bash in examples, Part 2: More about bash programming basics - in English , wait for translation
  • Bash in examples, Part 3: We consider the ebuild system - in English , the translation will be
To be continued ...



About Authors


Daniel Robbins


Дэниэль Роббинс — основатель сообщества Gentoo и создатель операционной системы Gentoo Linux. Дэниэль проживает в Нью-Мехико со свой женой Мэри и двумя энергичными дочерьми. Он также основатель и глава Funtoo, написал множество технических статей для IBM developerWorks, Intel Developer Services и C/C++ Users Journal.



Chris Houser


Крис Хаусер был сторонником UNIX c 1994 года, когда присоединился к команде администраторов университета Тэйлора (Индиана, США), где получил степень бакалавра в компьютерных науках и математике. После он работал во множестве областей, включая веб-приложения, редактирование видео, драйвера для UNIX и криптографическую защиту. В настоящий момент работает в Sentry Data Systems. Крис также сделал вклад во множество свободных проектов, таких как Gentoo Linux и Clojure, стал соавтором книги The Joy of Clojure.



Aron Griffis


Iron Griffis lives in Boston, where he spent the last decade working at Hewlett-Packard on projects such as UNIX network drivers for Tru64, Linux, Xen and KVM virtualization security certification, and most recently, the HP ePrint platform . In his spare time from programming, Ayron prefers to blot out over programming problems while riding his bicycle, juggling bits, or cheering for the Boston professional baseball team Red Socks.


Also popular now: