AWK Basic Tutorial
AWK is an interpreted programming language that is generally used to make shell scripts more powerful and feature-rich. It is mostly used to process data in text and file operations.
The name comes from the first letter of the surname of each of the creators: Alfred Aho, Peter Weinberger and Brian Kernighan.
This language is considered by many to be an important milestone in the history of programming, having had a great influence on the creation of other programming languages, such as Perl and Python.
- BWK: Also known as AWK or NAWK refers to the version by Brian Kernighan.
- GAWK: (GNU AWK) is another open source implementation (OPEN SOURCE)
- MAWK: It’s a much faster AWK implementation version by Mike Brennan (…)
The - f flag says that the following command is a program to execute.
For an executable program, use /usr/bin/awk.
For example, create a world.awk file with the content
Making this file executable
Save the dogs.txt File
Print entire file
$1prints the dog’s name,
We can use these variables within the print command. In it, whenever we put a comma, we are spacing
BEGIN, AWK doesn’t wait for an entry (like typing ENTER twice), it executes everything from that block.
- We use the - F flag to tell AWK that we will use the **CSV (comma separated values) **.
- As in language C, AWK also has the command printf, which is much more flexible than print.
The only thing print does that printf doesn’t do is automatically put a new line at the end of the string \n.
- sprintf: It acts and has the same syntax as printf. The difference is that its output is stored in a variable rather than displayed on the screen.
User Defined Variables
Cannot start variables by digits, they are case sensitive, must not have the same name as AWK variables, or other commands, and do not need to be initialized or declared.
When using the first variable, it is either an empty string (“”) or “0”, but it is not good to trust your script with these initial values.
AWK is poorly typed, that is, you can assign a number to a variable and then not assign a string, for example.
Ex .: Save as “dogs2.awk”
awk -f dogs2.awk dogs.txt
if and comparison operators
These are the control statements that control the flow of program execution in AWK. In AWK, they are similar to C, and have the same looping and interactions as the Shell pattern.
They are: if, while, for, do and the like.
Directing the exit
Create a file:
vim conditions.awk and insert this content:
awk -f conditions.awk gnu.txt
This was just an introduction to Awk, in the future we’ll see more tips.
Thanks for reading!
awk gawk linux command programming