Введение
Язык программирования AWK (/ɔː//k/) является стандартной функцией большинства Unix-подобных операционных систем. Язык AWK — это скриптовый язык, основанный на данных, состоящий из набора действий, предназначенных для обработки потоков текстовых данных — либо непосредственно из файлов, либо как часть конвейера — с целью извлечения или преобразования текста, например, для создания форматированных отчётов. Язык широко использует строковый тип данных, ассоциативные массивы (то есть массивы, индексированные строковыми ключами) и регулярные выражения. Несмотря на ограниченную область применения и первоначальную разработку для поддержки однострочных программ, язык является полным по Тьюрингу, и даже ранние пользователи AWK в Bell Labs часто писали хорошо структурированные большие программы на AWK. AWK был создан в Bell Labs в 1970-х годах, и его название образовано от фамилий его авторов: Альфреда Ахо (автора egrep), Питера Вайнбергера (работавшего над небольшими реляционными базами данных) и Брайана Кернигана. Акроним произносится так же, как название вида птиц олуша, который изображён на обложке книги «Язык программирования AWK». Будучи одним из первых инструментов, появившихся в Unix версии 7, AWK добавил вычислительные возможности в конвейер Unix, помимо оболочки Bourne, единственного доступного скриптового языка в стандартной среде Unix. Он является одним из обязательных компонентов спецификации Single UNIX Specification и требуется спецификацией Linux Standard Base. В 1983 году AWK был одним из нескольких инструментов UNIX, доступных для операционной системы UNOS компании Charles River Data Systems по лицензии Bell Laboratories. AWK был значительно переработан и расширен в 1985–1988 годах, что привело к созданию реализации GNU AWK, написанной Полом Рубином, Джеем Фенласоном и Ричардом Столлманом, выпущенной в 1988 году. GNU AWK поддерживается исключительно Арнольдом Роббинсом с 1994 года. Исходный код nawk (New AWK) Брайана Кернигана был впервые выпущен в 1993 году неофициально, а публично — в конце 1990-х годов; многие системы BSD используют его, чтобы избежать лицензии GPL. Программа AWK представляет собой последовательность пар «шаблон-действие», записанных следующим образом:
the programming language
AWK (/ɔː//k/ and is a standard feature of most Unix like operating systems. The AWK language is a data driven scripting language consisting of a set of actions to be taken against streams of textual data – either run directly on files or used as part of a pipeline – for purposes of extracting or transforming text, such as producing formatted reports. The language extensively uses the string datatype, associative arrays (that is, arrays indexed by key strings), and regular expressions. While AWK has a limited intended application domain and was especially designed to support one liner programs, the language is Turing complete, and even the early Bell Labs users of AWK often wrote well structured large AWK programs. AWK was created at Bell Labs in the 1970s, and its name is derived from the surnames of its authors: Alfred Aho (author of egrep), Peter Weinberger (who worked on tiny relational databases), and Brian Kernighan. The acronym is pronounced the same as the name of the bird species auk, which is illustrated on the cover of The AWK Programming Language. As one of the early tools to appear in Version 7 Unix, AWK added computational features to a Unix pipeline besides the Bourne shell, the only scripting language available in a standard Unix environment. It is one of the mandatory utilities of the Single UNIX Specification, and is required by the Linux Standard Base specification. In 1983, AWK was one of several UNIX tools available for Charles River Data Systems' UNOS operating system under Bell Laboratories license. AWK was significantly revised and expanded in 1985–88, resulting in the GNU AWK implementation written by Paul Rubin, Jay Fenlason, and Richard Stallman, released in 1988. because it is included with GNU based Linux packages. GNU AWK has been maintained solely by Arnold Robbins since 1994. Brian Kernighan's nawk (New AWK) source was first released in 1993 unpublicized, and publicly since the late 1990s; many BSD systems use it to avoid the GPL license. An AWK program is a series of pattern action pairs, written as:
condition { action }
condition { action }
where condition is typically an expression and action is a series of commands. The input is split into records, where by default records are separated by newline characters so that the input is split into lines. The program tests each record against each of the conditions in turn, and executes the action for each expression that is true. Either the condition or the action may be omitted. The condition defaults to matching every record. The default action is to print the record. This is the same pattern action structure as sed. In addition to a simple AWK expression, such as foo == 1 or /^foo/, the condition can be BEGIN or END causing the action to be executed before or after all records have been read, or pattern1, pattern2 which matches the range of records starting with a record that matches pattern1 up to and including the record that matches pattern2 before again trying to match against pattern1 on subsequent lines. In addition to normal arithmetic and logical operators, AWK expressions include the tilde operator, ~, which matches a regular expression against a string. As handy syntactic sugar, /regexp/ without using the tilde operator matches against the current record; this syntax derives from sed, which in turn inherited it from the ed editor, where / is used for searching. This syntax of using slashes as delimiters for regular expressions was subsequently adopted by Perl and ECMAScript, and is now common. The tilde operator was also adopted by Perl.
шаблон { действие }
шаблон { действие }
the programming language
AWK (/ɔː//k/ and is a standard feature of most Unix like operating systems. The AWK language is a data driven scripting language consisting of a set of actions to be taken against streams of textual data – either run directly on files or used as part of a pipeline – for purposes of extracting or transforming text, such as producing formatted reports. The language extensively uses the string datatype, associative arrays (that is, arrays indexed by key strings), and regular expressions. While AWK has a limited intended application domain and was especially designed to support one liner programs, the language is Turing complete, and even the early Bell Labs users of AWK often wrote well structured large AWK programs. AWK was created at Bell Labs in the 1970s, and its name is derived from the surnames of its authors: Alfred Aho (author of egrep), Peter Weinberger (who worked on tiny relational databases), and Brian Kernighan. The acronym is pronounced the same as the name of the bird species auk, which is illustrated on the cover of The AWK Programming Language. As one of the early tools to appear in Version 7 Unix, AWK added computational features to a Unix pipeline besides the Bourne shell, the only scripting language available in a standard Unix environment. It is one of the mandatory utilities of the Single UNIX Specification, and is required by the Linux Standard Base specification. In 1983, AWK was one of several UNIX tools available for Charles River Data Systems' UNOS operating system under Bell Laboratories license. AWK was significantly revised and expanded in 1985–88, resulting in the GNU AWK implementation written by Paul Rubin, Jay Fenlason, and Richard Stallman, released in 1988. because it is included with GNU based Linux packages. GNU AWK has been maintained solely by Arnold Robbins since 1994. Brian Kernighan's nawk (New AWK) source was first released in 1993 unpublicized, and publicly since the late 1990s; many BSD systems use it to avoid the GPL license. An AWK program is a series of pattern action pairs, written as:
condition { action }
condition { action }
where condition is typically an expression and action is a series of commands. The input is split into records, where by default records are separated by newline characters so that the input is split into lines. The program tests each record against each of the conditions in turn, and executes the action for each expression that is true. Either the condition or the action may be omitted. The condition defaults to matching every record. The default action is to print the record. This is the same pattern action structure as sed. In addition to a simple AWK expression, such as foo == 1 or /^foo/, the condition can be BEGIN or END causing the action to be executed before or after all records have been read, or pattern1, pattern2 which matches the range of records starting with a record that matches pattern1 up to and including the record that matches pattern2 before again trying to match against pattern1 on subsequent lines. In addition to normal arithmetic and logical operators, AWK expressions include the tilde operator, ~, which matches a regular expression against a string. As handy syntactic sugar, /regexp/ without using the tilde operator matches against the current record; this syntax derives from sed, which in turn inherited it from the ed editor, where / is used for searching. This syntax of using slashes as delimiters for regular expressions was subsequently adopted by Perl and ECMAScript, and is now common. The tilde operator was also adopted by Perl.
где шаблон обычно является выражением, а действие — набором команд. Входные данные разделяются на записи, при этом по умолчанию записи разделяются символами новой строки, то есть входные данные разбиваются на строки. Программа последовательно проверяет каждую запись на соответствие каждому из шаблонов и выполняет действие для каждого истинного выражения. Шаблон или действие могут быть опущены. Если шаблон опущен, по умолчанию происходит сопоставление с каждой записью. Действие по умолчанию — вывод записи. Эта структура «шаблон-действие» аналогична структуре sed. Помимо простого выражения AWK, такого как foo == 1 или /^foo/, шаблон может быть BEGIN или END, что приводит к выполнению действия до или после обработки всех записей, или pattern1, pattern2, что соответствует диапазону записей, начиная с записи, соответствующей pattern1, и заканчивая записью, соответствующей pattern2, после чего снова выполняется сопоставление с pattern1 в последующих строках. Помимо обычных арифметических и логических операторов, выражения AWK включают оператор тильды (~), который сопоставляет регулярное выражение со строкой. В качестве удобного синтаксического сахара /regexp/ без использования оператора тильды соответствует текущей записи; этот синтаксис был унаследован от sed, который, в свою очередь, унаследовал его от редактора ed, где символ / используется для поиска. Этот синтаксис использования слешей в качестве разделителей регулярных выражений впоследствии был принят Perl и ECMAScript и стал распространённым. Оператор тильды также был принят Perl.
the programming language
AWK (/ɔː//k/ and is a standard feature of most Unix like operating systems. The AWK language is a data driven scripting language consisting of a set of actions to be taken against streams of textual data – either run directly on files or used as part of a pipeline – for purposes of extracting or transforming text, such as producing formatted reports. The language extensively uses the string datatype, associative arrays (that is, arrays indexed by key strings), and regular expressions. While AWK has a limited intended application domain and was especially designed to support one liner programs, the language is Turing complete, and even the early Bell Labs users of AWK often wrote well structured large AWK programs. AWK was created at Bell Labs in the 1970s, and its name is derived from the surnames of its authors: Alfred Aho (author of egrep), Peter Weinberger (who worked on tiny relational databases), and Brian Kernighan. The acronym is pronounced the same as the name of the bird species auk, which is illustrated on the cover of The AWK Programming Language. As one of the early tools to appear in Version 7 Unix, AWK added computational features to a Unix pipeline besides the Bourne shell, the only scripting language available in a standard Unix environment. It is one of the mandatory utilities of the Single UNIX Specification, and is required by the Linux Standard Base specification. In 1983, AWK was one of several UNIX tools available for Charles River Data Systems' UNOS operating system under Bell Laboratories license. AWK was significantly revised and expanded in 1985–88, resulting in the GNU AWK implementation written by Paul Rubin, Jay Fenlason, and Richard Stallman, released in 1988. because it is included with GNU based Linux packages. GNU AWK has been maintained solely by Arnold Robbins since 1994. Brian Kernighan's nawk (New AWK) source was first released in 1993 unpublicized, and publicly since the late 1990s; many BSD systems use it to avoid the GPL license. An AWK program is a series of pattern action pairs, written as:
condition { action }
condition { action }
where condition is typically an expression and action is a series of commands. The input is split into records, where by default records are separated by newline characters so that the input is split into lines. The program tests each record against each of the conditions in turn, and executes the action for each expression that is true. Either the condition or the action may be omitted. The condition defaults to matching every record. The default action is to print the record. This is the same pattern action structure as sed. In addition to a simple AWK expression, such as foo == 1 or /^foo/, the condition can be BEGIN or END causing the action to be executed before or after all records have been read, or pattern1, pattern2 which matches the range of records starting with a record that matches pattern1 up to and including the record that matches pattern2 before again trying to match against pattern1 on subsequent lines. In addition to normal arithmetic and logical operators, AWK expressions include the tilde operator, ~, which matches a regular expression against a string. As handy syntactic sugar, /regexp/ without using the tilde operator matches against the current record; this syntax derives from sed, which in turn inherited it from the ed editor, where / is used for searching. This syntax of using slashes as delimiters for regular expressions was subsequently adopted by Perl and ECMAScript, and is now common. The tilde operator was also adopted by Perl.
Команды
Команды AWK — это операторы, которые подставляются вместо действия в приведенных выше примерах. Команды AWK могут включать вызовы функций, присваивания переменных, вычисления или любую их комбинацию. AWK имеет встроенную поддержку множества функций; ещё больше функций предоставляются различными версиями AWK. Кроме того, некоторые версии поддерживают подключение динамически подключаемых библиотек, которые также могут предоставлять дополнительные функции.