How to use AWK Command in Linux for Shell Scripting

Usefull Commands For Shell Scripting:-  There are few important Commands which are very useful to create any shell script. These commands helps us to create a script containing minimum number of lines to perform a very long task on linux.

Below are the few example commands:-

  1. awk
  2. sed
  3. find
  4. grep

Above commands can perform multiple tasks. And you can do experiments with them for your automation purpose.

I will try to explore them with few examples below to understand.

  1. What is AWK :- The AWK for Aho, Weinberger and Kernighan, the authors of the language, which was started in 1977. And awk is not just a command to run. It works like a complete scripting tool in itself.We can perform multiple complex operations with it.This tool awk is used to extract data from any input to it. And the input can be any file or any command’s output.
  2. How to use awk command ?Below is the awk command syntax:awk (condition) (action)So here we will first mention the “condition or delimeter or field seperator” just after awk following with the option -F.
    And then we will mention the action to be done on that condition matched event.

    so let us try one simple example to understand the awk tool.

    First we will create a file in /tmp named as contentfile. And put some data in it arranged in columns.

    vim /tmp/contentfile

    Name Age Gender

    akash 30 Male
    ayush 35 Male
    arun 32 Male
    vishal 40 Male

    :wq! (save and exit this file)

    Now if we want to show the data of this file then will run below command without opening this file

    cat /tmp/contentfile

    OUTPUT:-

    Name Age Gender

    akash 30 Male
    ayush 35 Male
    arun 32 Male
    vishal 40 Male

    But if we need to show only the name and age to the user then below is the command to perform this action using awk.

    cat /tmp/contentfile | awk -F ” ” ‘{print $1″:”$2}’
    OR
    awk -F ” ” ‘{print $1″:”$2}’ /tmp/contentfile

    OUTPUT:-

    Name:Age

    akash:30
    ayush:35
    arun:32
    vishal:40

    Components of above command:-

go4linux

Later we will post some more examples on AWK and other useful commands as well.

Enjoy scripting 😉

One thought on “How to use AWK Command in Linux for Shell Scripting

  • August 16, 2016 at 10:46 am
    Permalink

    Oh my goodness! Incredible article dude! Many thanks. 

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *