8 Levels of Using awk in Linux
Explaining with simple examples
--
There is one command in Linux which is too powerful to be called a command — awk. It’s literally a scripting language for text handling in Linux.
Mastering the awk
is a long-term journey since it has lots of options, syntax and complex usages. Of course, you can go to its official user manual page and check them out. But its manual is a super long page, isn’t it? Few people can read it all at once.
This is why this article will make your life easier 🙂. It’s not necessary to remember all its options and syntax. All you need to know are what it can do and some common usages.
This article, based on my own experience, will introduce you common and minimum knowledge you need for using awk
in 8 levels of difficulty.
0. Understanding the Structure of awk Commands
Basically, everything will be started from an awk
keyword, then there is an awk
program enclosed in single quotes. At the end, it’s the name of a file that this awk
command will handle.
Inside the single quotes, there are two types of programs: “patterns” and “actions”. A pattern is used to search certain text on a file. An action, as its name says, is used to do some operations.
So, there are three types of uses of awk
:
1. Only execute an action
awk '{action}' filename
2. Only search text based on a pattern
awk 'pattern' filename
3. Combine the uses of patterns and actions
awk 'pattern {action}' filename
As shown above, to distinguish patterns and actions, an action will be enclosed with curly braces.
Now, we have the basic background knowledge of awk
already. Let’s dive into more details of its usages.
1. Running Actions Directly
Here is a file named yang.txt
which will be the example file of this article. Its contents are: