Tutorial [Linux] Basics of AWK
#1
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.
Reply
#2
Awesome tutorial x86Cow Smile Thank you for taking your time and sharing with us.
Reply
#3
Dude, this can save my life. Thank you very much.
Reply
#4
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help choosing my linux OS Knife Boss 15 34,428 07-17-2021, 02:44 AM
Last Post: x86Cow
  What OS or Linux distro is everyone using around here? Kontu 60 156,481 07-08-2021, 02:45 AM
Last Post: violator
  System Calls under Linux Insider 1 10,310 07-05-2021, 07:59 PM
Last Post: x86Cow
  Linux Journey -- A beginner's resource for learning Linux Cypher 3 14,799 07-05-2021, 07:58 PM
Last Post: x86Cow