Tutorial [Linux] Basics of AWK
Basics of AWK
AWK is a command line tool used for text stream manipulation. It comes by default on most if not all Linux distributions. Awk parses documents using columns.

The basic syntax for awk is:
Code [Expanded]:
awk <flags> '{subcommand}' file.txt

In the curly brackets you write what exactly you want awk to do. For example the most basic command is print.
Code [Expanded]:
awk '{print}' file
The print command with out anything else just prints the file (same as cat).

To parse columns with awk you use $ and the column number. In this example we will use the ps command.
Code [Expanded]:
ps | awk '{print $1}'
If you are unfamiliar with pipes ( | ) they are used to take the output of one command and use it as the input of the command after.

If you do not want the separator to be a space you can use the -F flag. in this example we will use /etc/passwd file
Code [Expanded]:
awk -F ':' '{print $1} /etc/passwd

In this file it uses colons to separate the columns. so " -F ':'" tells awk to use colon as the separator. The output of this command will print out all users on the system.

If you are working with larger files and do not want to count to find the last column you can use $NF
Code [Expanded]:
awk -F '/' '{print $NF}' /etc/shells

Awk can even add numbers if you needed it too.
Code [Expanded]:
ps | awk '{s+=$1} END {print s}

this command adds the numbers outputted in the first column of the ps command and saves it to a variable "s". Then it prints the variable "s".

These are some basic things you can do with awk. Feel free to ask any questions and I will get back to you as soon as I can.
Awesome tutorial x86Cow Smile Thank you for taking your time and sharing with us.
Dude, this can save my life. Thank you very much.
(07-05-2021, 04:43 PM)Corvo Wrote: Dude, this can save my life. Thank you very much.

Awesome to hear! Glad to help, feel free to contact me with any questions and I will reply asap.

Possibly Related Threads…
Thread Author Replies Views Last Post
  What OS or Linux distro is everyone using around here? Kontu 63 242,968 12-28-2021, 10:07 AM
Last Post: _BNM57_
  Help choosing my linux OS Knife Boss 15 59,944 07-17-2021, 02:44 AM
Last Post: x86Cow
  System Calls under Linux Insider 1 18,884 07-05-2021, 07:59 PM
Last Post: x86Cow
  Linux Journey -- A beginner's resource for learning Linux Cypher 3 23,965 07-05-2021, 07:58 PM
Last Post: x86Cow