File wildcards in linux

Linux Tutorial — 7. Wildcards

In the section on File Manipulation we learnt about a few commands to do interesting things. The problem was that they all operated on a single file at a time, not very efficient. Now I’m going to introduce a means to play about with a set of files at once.

So what are they?

Wildcards are a set of building blocks that allow you to create a pattern defining a set of files or directories. As you would remember, whenever we refer to a file or directory on the command line we are actually referring to a path. Whenever we refer to a path we may also use wildcards in that path to turn it into a set of files or directories.

Here is the basic set of wildcards:

  • * — represents zero or more characters
  • ? — represents a single character
  • [] — represents a range of characters

As a basic first example we will introduce the *. In the example below we will list every entry beginning with a b.

  1. pwd
  2. /home/ryan/linuxtutorialwork
  3. ls
  4. barry.txt blah.txt bob example.png firstfile foo1 foo2
  5. foo3 frog.png secondfile thirdfile video.mpeg
  6. ls b*
  7. barry.txt blah.txt bob

Under the Hood

The mechanism here is actually kinda interesting. On first glance you may assume that the command above ( ls ) receives the argument b* then proceeds to translate that into the required matches. It is actually bash (The program that provides the command line interface) that does the translation for us. When we offer it this command it sees that we have used wildcards and so, before running the command ( in this case ls ) it replaces the pattern with every file or directory (ie path) that matches that pattern. We issue the command:

Then the system translates this into:

and then executes the program. The program never sees the wildcards and has no idea that we used them. This is funky as it means we can use them on the command line whenever we want. We are not limited to only certain programs or situations.

Some more examples

Some more examples to illustrate their behaviour. For all the examples below, assume we are in the directory linuxtutorialwork and that it contains the files as listed above. Also note that I’m using ls in these examples simply because it is a convenient way to illustrate their usage. Wildcards may be used with any command.

Читайте также:  Как редактировать файл в терминале линукс

Every file with an extension of txt at the end. In this example we have used an absolute path. Wildcards work just the same if the path is absolute or relative.

  1. ls /home/ryan/linuxtutorialwork/*.txt
  2. /home/ryan/linuxtutorialwork/barry.txt /home/ryan/linuxtutorialwork/blah.txt

Now let’s introduce the ? operator. In this example we are looking for each file whose second letter is i. As you can see, the pattern can be built up using several wildcards.

Or how about every file with a three letter extension. Note that video.mpeg is not matched as the path name must match the given pattern exactly.

And finally the range operator ( [ ] ). Unlike the previous 2 wildcards which specified any character, the range operator allows you to limit to a subset of characters. In this example we are looking for every file whose name either begins with a s or v.

With ranges we may also include a set by using a hyphen. So for example if we wanted to find every file whose name includes a digit in it we could do the following:

We may also reverse a range using the caret ( ^ ) which means look for any character which is not one of the following.

Some Real World Examples

The examples above illustrate how the wildcards work but you may be wondering what use they actually are. People use them everywhere and as you progress I’m sure you’ll find many ways in which you can use them to make your life easier. Here are a few examples to give you a taste of what is possible. Remember, these are just a small sample of what is possible, and they can be used whenever you specify a path on the command line. With a little creative thinking you’ll find they can be used in all manner of situations.

Find the file type of every file in a directory.

  1. file /home/ryan/*
  2. bin: directory
  3. Documents: directory
  4. frog.png: PNG image data
  5. public_html: directory

Move all files of type either jpg or png (image files) into another directory.

Find out the size and modification time of the .bash_history file in every users home directory. (.bash_history is a file in a typical users home directory that keeps a history of commands the user has entered on the command line. Remember how the . means it is a hidden file?) As you can see in this example, we may use wildcards at any point in the path.

  1. ls -lh /home/*/.bash_history
  2. -rw——- 1 harry users 2.7K Jan 4 07:32 /home/harry/.bash_history
  3. -rw——- 1 ryan users 3.1K Jun 12 21:16 /home/ryan/.bash_history

Summary

No new commands introduced in this section.

Anywhere in any path Wildcards may be used at any part of a path. Wherever a path is used Because wildcard substitution is done by the system, not the command, they may be used wherever a path is used.

Activities

Let’s play with some patterns.

  • A good directory to play with is /etc which is a directory containing config files for the system. As a normal user you may view the files but you can’t make any changes so we can’t do any harm. Do a listing of that directory to see what’s there. Then pick various subsets of files and see if you can create a pattern to select only those files.
  • Do a listing of /etc with only files that contain an extension.
  • What about only a 3 letter extension?
  • How about files whose name contains an uppercase letter? (hint: [[:upper:]] may be useful here)
  • Can you list files whose name is 4 characters long?
  • Section Breakdown
  • Introduction
  • So what are they?
  • Under the Hood
  • More Examples
  • Real World Examples
  • Summary
  • Activities
  • Next Section
  • Permissions
Читайте также:  Объединить два файла linux

Источник

Шаблоны подстановки в Linux

Шаблоны подстановки (wildcards) позволяют настраивать фильтры отбора имён файлов и путей. В интернете вы можно встретить и такие названия: джокеры, шаблоны поиска, маски (хотя на самом деле это немного другое).

Как вы помните, когда мы обращаемся к файлу или каталогу в командной строке, мы фактически ссылаемся на его путь. Поэтому когда мы указываем путь, можно использовать так называемые символы подстановки в этом пути, чтобы превратить его в набор файлов или каталогов.

Вот основной набор символов подстановки:

  • * — для замены нескольких символов (в том числе 0);
  • ? — для замены одиночного символа;
  • [ ] — для замены определенного набора символов.

Символы подстановки также называют символами-джокерами.

Символ подстановки *

Давайте рассмотрим несколько примеров, которые продемонстрируют, как работает символ подстановки * (звёздочка). Он представляет собой несколько символов (в том числе 0).

Примечание. Для всех приведенных ниже примеров представьте, что мы находимся в каталоге linuxtutorialwork, в котором находятся такие файлы:
• barry.txt, blah.txt;
• bob;
• firstfile, secondfile, thirdfile;
• foo1, foo2, foo3;
• video.mpeg.

Пример 1. Выводим названия файлов, начинающихся с b

В качестве первого примера попробуем вывести все файлы, чьё название начинается с b.

1. [email protected]: pwd
2. /home/karpaff/linuxtutorialwork
3. [email protected]:
4. [email protected]: ls b*
5. barry.txt blah.txt bob
6. [email protected]:

Как это работает

На первый взгляд может показаться, что приведенная выше команда ls получает аргумент b* , а затем переводит его в требуемые совпадения.

На самом деле это bash (программа, предоставляющая интерфейс командной строки) выполняет перевод за нас. Когда мы вводим эту команду, bash видит, что мы использовали символы подстановки, и поэтому перед запуском команды (в данном случае ls ) заменяет шаблон каждым файлом или каталогом (то есть путем), который соответствует этому шаблону.

  1. Мы вводим команду: ls b*
  2. Система переводит эту команду в такой вид: ls barry.txt blah.txt bob
  3. Система выполняет команду из пункта 2.

Сама команда не видит символы подстановки и не знает, что мы их применяли. Это означает, что мы можем использовать их в командной строке когда угодно.

Примечание. Обратите внимание, что мы используем ls в примерах просто потому, что это удобный способ проиллюстрировать работу подстановки. Символы подстановки можно использовать с любой командой.

Пример 2. Выводим все файлы с расширением .txt

Давайте попробуем вывести все файлы с расширением .txt . В этом примере мы используем абсолютный путь. Обратите внимание, что шаблон подстановки работает одинаково, и с абсолютными, и с относительными путями.

1. [email protected]: ls /home/karpaff/linuxtutorialwork/*.txt
2. /home/karpaff/linuxtutorialwork/barry.txt /home/karpaff/linuxtutorialwork/blah.txt
3. [email protected]:

Символ подстановки ?

Теперь давайте рассмотрим, как работает символ ? (знак вопроса). Он представляет собой 1 любой символ.

Пример 3. Выводим все файлы с именем, вторая символ которого — i

В примере ниже мы выведем все файлы с именем, второй символ равен i. Как видите, шаблон можно строить с помощью нескольких символов подстановки.

1. [email protected]: ls ?i*
2. firstfile video.mpeg
3. [email protected]:

Пример 4. Выводим все файлы с расширением из 3 букв

Теперь выведем все файлы с расширением из трех букв. Обратите внимание, что video.mpeg не подходит, поскольку имя пути должно точно соответствовать заданному шаблону.

1. [email protected]: ls *. 
2. barry.txt blah.txt example.png frog.png
3. [email protected]:

Символ подстановки []

И, наконец, символ подстановки [] (квадратные скобки) — для диапазона. В отличие от двух предыдущих символов подстановки, которые позволяли задать несколько символов, [] позволяет задать набор символов.

Читайте также:  What is linux kernel firmware

Давайте выведем все файлы, имя которых начинается с s или v.

Пример 5. Выводим все файлы, имя которых начинается с s или v

1. [email protected]: ls [sv]*
2. secondfile video.mpeg
3. [email protected]:

В диапазон можно включить готовые наборы символов, используя дефис. Например, если мы хотим вывести каждый файл, имя которого включает в себя цифру, можно использовать диапазон 2 .

Пример 6. Выводим все файлы, в имени которых есть хотя бы 1 цифра

1. [email protected]: ls *3*
2. foo1 foo2 foo3
3. [email protected]:

Инвертированный диапазон

Мы также можем использовать инвертированный диапазон, используя знак ^ (каретка). Он позволяет искать символы, которые не входят в заданный диапазон.

1. [email protected]: ls [^a-k]*
2. secondfile thirdfile video.mpeg
3. [email protected]:

Примеры из реальной жизни

Приведенные выше примеры иллюстрируют работу символов подстановки. В реальной работе люди используют их повсюду, поэтому вот несколько примеров, которые покажут вам, что еще можно делать с шаблонами.

Помните, что это лишь небольшие кейсы, в которых могут пригодиться wildcards. На самом деле, шаблоны удобно использовать в практически любой ситуации.

Пример 8. Выводим тип файла для каждого файла или папки в каталоге

1. [email protected]: file /home/karpaff/*
2. bin: directory
3. Documents: directory
4. frog.png: PNG image data
5. public_html: directory
6. [email protected]:

Пример 9. Перемещаем все файлы типа jpg или png в другой каталог.

1. [email protected]: mv public_html/*. g public_html/images/
2. [email protected]:

Пример 10. Узнаем размер и время изменения файла .bash_history в домашнем каталоге пользователя

.bash_history — это файл в домашнем каталоге пользователя, который хранит историю команд, введенных пользователем в командной строке. Это скрытый файл.

Как вы можете видеть в этом примере, мы можем использовать подстановочные знаки в любой точке пути.

1. [email protected]: ls -lh /home/*/.bash_history
2. -rw------- 1 harry users 2.7K Jan 4 07:32 /home/karpaff/.bash_history
3. -rw------- 1 ryanusers 3.1K Jun 12 21:16 /home/andrew/.bash_history
4. [email protected]:

Что нужно запомнить

Можно использовать в любом месте пути файла
Символы подстановки могут использоваться в любой части пути.

Можно использовать везде, где есть путь
Поскольку подстановка символов выполняется системой, а не командой, шаблоны подстановки могут использоваться везде, где используется путь.

Практические задания

Хороший каталог, на котором можно попрактиковаться — это /etc, который содержит файлы конфигурации системы. Как обычный пользователь, вы можете просматривать файлы, но не можете вносить какие-либо изменения, поэтому случайно повредить данный каталог не получится.

Выведите содержимое каталога и посмотрите, что там находится. Затем выберите несколько файлов и подумайте, можно ли создать шаблон для выбора только этих файлов.

  1. Выведите список файлов с определенным расширением.
  2. Выведите файлы, расширение которых состоит только из трех букв.
  3. Выведите файлы, имя которых содержит заглавную букву (подсказка: используйте конструкцию [[: upper:]])
  4. Выведите файлы, имя которых состоит из четырех символов.

СodeСhick.io — простой и эффективный способ изучения программирования.

2023 © ООО «Алгоритмы и практика»

Источник

Оцените статью
Adblock
detector