Команды с использованием конвейера |
- Statistics
- Participants
- Translate into Russian
- Translation result
- 38% translated in draft.
Конвейер (pipe) позволяет работать программам вместе, подключая вывод одной программы ко входным данным другой. Конвейер делается с помощью вертикальной черты (|)
К примеру, Вы хотите помочь эксцентричной тёте Гартензии управлять своей частной коллекцией книг. У Вас есть файл с названиями книг, каждая строка которого имеет вид 'Автор:Заголовок', что-то вроде этого:
$ cat books
Carroll, Lewis:Through the Looking-Glass
Shakespeare, William:Hamlet
Bartlett, John:Familiar Quotations
Mill, John Stuart:On Nature
London, Jack:John Barleycorn
Bunyan, John:Pilgrim's Progress, The
Defoe, Daniel:Robinson Crusoe
Mill, John Stuart:System of Logic, A
Milton, John:Paradise Lost
Johnson, Samuel:Lives of the Poets
Shakespeare, William:Julius Caesar
Mill, John Stuart:On Liberty
Bunyan, John:Saved by Grace
Это немного неопрятно, т.к. они идут не по порядку. Но вы можете использовать команду sort для упорядочивания списка:
$ sort books
Bartlett, John:Familiar Quotations
Bunyan, John:Pilgrim's Progress, The
Bunyan, John:Saved by Grace
Carroll, Lewis:Through the Looking-Glass
Defoe, Daniel:Robinson Crusoe
Johnson, Samuel:Lives of the Poets
London, Jack:John Barleycorn
Mill, John Stuart:On Liberty
Mill, John Stuart:On Nature
Mill, John Stuart:System of Logic, A
Milton, John:Paradise Lost
Shakespeare, William:Hamlet
Shakespeare, William:Julius Caesar
Теперь у Вас есть список, отстортированый по автору. Как насчет того, чтобы получить список только с авторами, без заголовков? Вы можете это сделать с помощью команды cut:
$ cut -d: -f1 books
Carroll, Lewis
Shakespeare, William
Bartlett, John
Mill, John Stuart
London, Jack
Bunyan, John
Defoe, Daniel
Mill, John Stuart
Milton, John
Johnson, Samuel
Shakespeare, William
Mill, John Stuart
Bunyan, John
A little explanation here. The -d option chose a colon as the delimiter (separator). This tells cut to break up each line wherever a delimiter appears, and each separate part of the line is called a field. In our format, the author's name appears as the first field, so we have put a 1 with the -f option to tell cut that we want to see just that field.
Но Ваш список опять не отсортирован.
Конвейер исправит это!
$ sort books | cut -d: -f1
Bartlett, John
Bunyan, John
Bunyan, John
Carroll, Lewis
Defoe, Daniel
Johnson, Samuel
London, Jack
Mill, John Stuart
Mill, John Stuart
Mill, John Stuart
Milton, John
Shakespeare, William
Shakespeare, William
Voila! Вы взяли отсортированый по алфавиту список, который является выводом команды sort, и передали его как входные данные команде cut.
Не указывайте имя файла для cut, так как Вы хотите совершать операции над выводом команды sort.
Конвейер работает просто - текст передается через pipe от одной команды к следующей.
Что если Вы хотите получить отсортированный список по названиям? Т.к название книги находится в поле 2, давайте попробуем подставить -f2 вместо -f1:
$ sort books | cut -d: -f2
Familiar Quotations
Pilgrim's Progress, The
Saved by Grace
Through the Looking-Glass
Robinson Crusoe
Lives of the Poets
John Barleycorn
On Liberty
On Nature
System of Logic, A
Paradise Lost
Hamlet
Julius Caesar
Ой-ой. Что случилось? Глядя на конвейер, Вам нужно пройтись слева-направо. В данном случае, мы отсортировали файл перед тем, как выбрать из него названия книг. Строки сортировались правильно, т.к. имя автора идет первым. Для того чтобы получить названия в надлежащем порядке, Вам нужно сортировать после их извлечения:
$ cut -d: -f2 books | sort
Familiar Quotations
Hamlet
John Barleycorn
Julius Caesar
Lives of the Poets
On Liberty
On Nature
Paradise Lost
Pilgrim's Progress, The
Robinson Crusoe
Saved by Grace
System of Logic, A
Through the Looking-Glass
Much better. Now this is all very nice, but you may be thinking you could have done these things with a spreadsheet. For simpler tasks, this is probably true. But suppose that Aunt Hortense is in the habit of asking odd questions about her collection. For example, she wants to know how many books she has from each author named John. A spreadsheet or other graphical program may have difficulty handling a request that wasn't anticipated by the program's authors. But the shell offers us many small, simple commands that can be combined in unforeseen ways to accomplish a complex task.
To find a particular string in a line of text, use the grep command. Now remember that when you combine commands, they need to go in the proper order. You can't run grep against the file first, because it will match the title 'John Barleycorn' in addition to authors named John. So add it to the end of the pipeline:
$ cut -d: -f1 books | sort | grep "John"
Bartlett, John
Bunyan, John
Bunyan, John
