Awk: Difference between revisions

From TÜ Narva Kolledži Wiki
Jump to navigation Jump to search
Content deleted Content added
Dzikajev (talk | contribs)
No edit summary
m Reverted edits by Dzikajev (talk) to last revision by 185.153.146.177
Tag: Rollback
 
(One intermediate revision by one other user not shown)
Line 1: Line 1:
Igor Džikajev
<h1>Команда AWK</h1>
<h1>What is <span style="background:gray;padding:2px;border-radius:5px;color:white;">awk</span> command?</h1>
AWK - это скриптовый язык, который не требует компиляции и используется прямо в командной строке, применяемый при фильтрации и обработке текста.
<span style="background:gray;padding:2px;border-radius:5px;color:white;">awk</span> is a scripting language, and it is helpful when working in the command line. It's also a widely used command for text processing.
When using <span style="background:gray;padding:2px;border-radius:5px;color:white;">awk</span>, you are able to select data – one or more pieces of individual text – based on a pattern you provide.


For example, some of the operations you can do with <span style="background:gray;padding:2px;border-radius:5px;color:white;">awk</span> are searching for a specific word or pattern in a piece of text given, or even select a certain line or a certain column in a file you provide.
Работает она таким образом, что читает файл по строчке за раз и выполняет указанное действие выводя результат.

<h1>Использование команды AWK</h1>
<h1>The Basic Syntax of the <span style="background:gray;padding:2px;border-radius:5px;color:white;">awk</span> command</h1>
Синтакс AWK выглядит так: <b>awk параметры 'действие' исходный_файл</b> <br>
In its simplest form, the <span style="background:gray;padding:2px;border-radius:5px;color:white;">awk</span> command is followed by a set of single quotation marks and a set of curly braces, with the name of the file you want to search through mentioned last.
Если написать awk в терминал, то выдаст такое применение:[[File:Igor_awksyntax.png]] <br>

Все возможные параметры команды AWK:
It looks something like this:
[[file:Igor_awk_options.png|552px]]
<p style="background:rgba(50,50,50,0.1);padding:10px;">awk '{action}' your_file_name.txt</p>
<h2>Примеры использования</h2>
When you want to search for text that has a specific pattern or you're looking for a specific word in the text, the command would look something like this:
[[File:Igor_catanyfile.png]] <br>
<p style="background:rgba(50,50,50,0.1);padding:10px;">awk '/regex pattern/{action}' your_file_name.txt</p>
Имея такой файл и используя <b>awk '{print $3}' anyfile</b>, я получу такой вывод:[[file:Igor_awk_3rdcol.png]], то есть, выписался только 3-тий столбик, так же этот вывод перенаправить в файл добавив <b>> any_other_file</b> к концу, название файла может быть любым

Однако этим использование команды AWK не заканчивается, так же можно использовать <b>регулярные выражения</b>:
With information.txt file looking like this:
[[file:Igor_regex_awk.png]], тут выписываются весь файл *<b>{print $0}</b>*, но регулярным выражением мы указали что только строчки содержащие "I"
<p style="background:rgba(50,50,50,0.1);padding:10px;white-space:pre;">fristName lastName age city ID
NR: Команда NR ведет текущий подсчет количества входных записей. Помните, что записи обычно представляют собой строки. Команда Awk выполняет операторы шаблона/действия один раз для каждой записи в файле.

<ul>
Thomas Shelby 30 Rio 400
<li>NF: Команда NF подсчитывает количество полей в текущей входной записи.
Omega Night 45 Ontario 600
<li>FS: команда FS содержит символ-разделитель полей, который используется для разделения полей в строке ввода. По умолчанию используется «пробел», что означает пробел и символы табуляции. FS можно переназначить другому символу (обычно в BEGIN), чтобы изменить разделитель полей.
Wood Tinker 54 Lisbon N/A
<li>RS: Команда RS сохраняет текущий символ разделителя записи. Поскольку по умолчанию входная строка является входной записью, символом разделителя записей по умолчанию является новая строка.
Giorgos Georgiou 35 London 300
<li>OFS: команда OFS сохраняет разделитель полей вывода, который разделяет поля, когда Awk их печатает. По умолчанию это пустое место. Всякий раз, когда print имеет несколько параметров, разделенных запятыми, между каждым параметром будет напечатано значение OFS.
Timmy Turner 32 Berlin N/A</p>
<li>ORS: Команда ORS сохраняет разделитель выходных записей, который разделяет выходные строки, когда Awk их печатает. По умолчанию используется символ новой строки. print автоматически выводит содержимое ORS в конце всего, что было передано для печати.
<h6>We are able to</h6>
<ul style="list-style:none;>
<li>Print all the contents of the file using <span style="background:rgba(50,50,50,0.1);padding:5px;">awk '{print $0}' information.txt</span>
<li>Add incrementing number before each line using <span style="background:rgba(50,50,50,0.1);padding:5px;">awk '{print NR,$0}' information.txt</span>
<li>Print specific columns using <span style="background:rgba(50,50,50,0.1);padding:5px;">awk '{print $1}' information.txt</span> *number represents column* It is also possible to print out multiple by adding $n after $1 <span style="background:rgba(50,50,50,0.1);padding:5px;">awk '{print $1, $4}' information.txt</span> or $NF to print out last column
</span>
<li>Print specific lines of a column by adding <span style="background:rgba(50,50,50,0.1);padding:5px;">head or tail command to existing command // awk '{print $1}' information.txt | head -1 </span>
<li>Use regex <span style="background:rgba(50,50,50,0.1);padding:5px;">awk ' /io/{print $0}' information.txt</span> this will print out lines containing "io"
<li>Use comparisson operators <span style="background:rgba(50,50,50,0.1);padding:5px;">awk '$3 < 40 { print $0 }' information.txt</span> this will only print out lines where 3rd column (age) is <40
</ul>
</ul>
This wraps up everything there is to say about <span style="background:gray;padding:2px;border-radius:5px;color:white;">awk</span>.

Latest revision as of 07:04, 22 August 2023

Igor Džikajev

What is awk command?

awk is a scripting language, and it is helpful when working in the command line. It's also a widely used command for text processing. When using awk, you are able to select data – one or more pieces of individual text – based on a pattern you provide.

For example, some of the operations you can do with awk are searching for a specific word or pattern in a piece of text given, or even select a certain line or a certain column in a file you provide.

The Basic Syntax of the awk command

In its simplest form, the awk command is followed by a set of single quotation marks and a set of curly braces, with the name of the file you want to search through mentioned last.

It looks something like this:

awk '{action}' your_file_name.txt

When you want to search for text that has a specific pattern or you're looking for a specific word in the text, the command would look something like this:

awk '/regex pattern/{action}' your_file_name.txt

With information.txt file looking like this:

fristName lastName age city ID Thomas Shelby 30 Rio 400 Omega Night 45 Ontario 600 Wood Tinker 54 Lisbon N/A Giorgos Georgiou 35 London 300 Timmy Turner 32 Berlin N/A

We are able to
  • Print all the contents of the file using awk '{print $0}' information.txt
  • Add incrementing number before each line using awk '{print NR,$0}' information.txt
  • Print specific columns using awk '{print $1}' information.txt *number represents column* It is also possible to print out multiple by adding $n after $1 awk '{print $1, $4}' information.txt or $NF to print out last column
  • Print specific lines of a column by adding head or tail command to existing command // awk '{print $1}' information.txt | head -1
  • Use regex awk ' /io/{print $0}' information.txt this will print out lines containing "io"
  • Use comparisson operators awk '$3 < 40 { print $0 }' information.txt this will only print out lines where 3rd column (age) is <40

This wraps up everything there is to say about awk.