Showing posts with label Linux awk. Show all posts
Showing posts with label Linux awk. Show all posts

Thursday, 8 August 2019

Linoux - How To Use awk In Bash Scripting

Print a Text File

awk '{ print }' /etc/passwd
OR
awk '{ print $0 }' /etc/passwd

Print Specific Field

Use : as the input field separator and print first field only i.e. usernames (will print the the first field. all other fields are ignored):
awk -F':' '{ print $1 }' /etc/passwd
Send output to sort command using a shell pipe:
awk -F':' '{ print $1 }' /etc/passwd | sort

Pattern Matching

You can only print line of the file if pattern matched. For e.g. display all lines from Apache log file if HTTP error code is 500 (9th field logs status error code for each http request):
awk '$9 == 500 { print $0}' /var/log/httpd/access.log
The part outside the curly braces is called the “pattern”, and the part inside is the “action”. The comparison operators include the ones from C:
== != < > <= >= ?:
If no pattern is given, then the action applies to all lines. If no action is given, then the entire line is printed. If “print” is used all by itself, the entire line is printed. Thus, the following are equivalent:
awk '$9 == 500 ' /var/log/httpd/access.log
awk '$9 == 500 {print} ' /var/log/httpd/access.log
awk '$9 == 500 {print $0} ' /var/log/httpd/access.log

Print Lines Containing tom, jerry AND vivek

Print pattern possibly on separate lines:
awk '/tom|jerry|vivek/' /etc/passwd

Print 1st Line From File

awk "NR==1{print;exit}" /etc/resolv.conf
awk "NR==$line{print;exit}" /etc/resolv.conf

Simply Arithmetic

You get the sum of all the numbers in a column:
awk '{total += $1} END {print total}' earnings.txt
Shell cannot calculate with floating point numbers, but awk can:
awk 'BEGIN {printf "%.3f\n", 2005.50 / 3}'

Call AWK From Shell Script

A shell script to list all IP addresses that accessing your website. This script use awk for processing log file and verification is done using shell script commands.
#!/bin/bash
d=$1
OUT=/tmp/spam.ip.$$
HTTPDLOG="/www/$d/var/log/httpd/access.log"
[ $# -eq 0 ] && { echo "Usage: $0 domain-name"; exit 999; }
if [ -f $HTTPDLOG ];
then
 awk '{print}' $HTTPDLOG >$OUT
 awk '{ print $1}' $OUT  |  sort -n | uniq -c | sort -n
else
 echo "$HTTPDLOG not found. Make sure domain exists and setup correctly."
fi
/bin/rm -f $OUT

AWK and Shell Functions

Here is another example. chrootCpSupportFiles() find out the shared libraries required by each program (such as perl / php-cgi) or shared library specified on the command line and copy them to destination. This code calls awk to print selected fields from the ldd output:
chrootCpSupportFiles() {
# Set CHROOT directory name
local BASE="$1"         # JAIL ROOT
local pFILE="$2"        # copy bin file libs
 
[ ! -d $BASE ] && mkdir -p $BASE || :
 
FILES="$(ldd $pFILE | awk '{ print $3 }' |egrep -v ^'\(')"
for i in $FILES
do
  dcc="$(dirname $i)"
  [ ! -d $BASE$dcc ] && mkdir -p $BASE$dcc || :
  /bin/cp $i $BASE$dcc
done
 
sldl="$(ldd $pFILE | grep 'ld-linux' | awk '{ print $1}')"
sldlsubdir="$(dirname $sldl)"
if [ ! -f $BASE$sldl ];
then
        /bin/cp $sldl $BASE$sldlsubdir
else
        :
fi
}
This function can be called as follows:
chrootCpSupportFiles /lighttpd-jail /usr/local/bin/php-cgi

AWK and Shell Pipes

List your top 10 favorite commands:
history | awk '{print $2}' | sort | uniq -c | sort -rn | head
Sample Output:
   172 ls
    144 cd
     69 vi
     62 grep
     41 dsu
     36 yum
     29 tail
     28 netstat
     21 mysql
     20 cat
Another example to find out domain expiry date:
$ whois cyberciti.com | awk '/Registry Expiry Date:/ { print $4 }'
Sample outputs:
2018-07-31T18:42:58Z

Awk Program File

You can put all awk commands in a file and call the same from a shell script using the following syntax:
awk -f mypgoram.awk input.txt

Awk in Shell Scripts – Passing Shell Variables TO Awk

You can pass shell variables to awk using the -v option:
n1=5
n2=10
echo | awk -v x=$n1 -v y=$n2 -f program.awk
Assign the value n1 to the variable x, before execution of the program begins. Such variable values are available to the BEGIN block of an AWK program:
BEGIN{ans=x+y}
{print ans}
END{}

AWK command in Linux/Unix

What Operations can AWK do?

  • Scanning files line by line
  • Splitting each input line into fields
  • Comparing input lines and fields to patterns
  • Performing specified actions on matching lines

AWK Command Usefulness

  • Changing data files
  • Producing formatted reports

Programming Concepts for awk command

  • Format output lines
  • Conditional and loops
  • Arithmetic and string operations

AWK Syntax

$ awk options 'selection _criteria {action }' input-file > output-file
To demonstrate more about AWK usage, we are going to use the text file called file.txt
awk command example file
1st column => Item,
2nd column => Model
3rd column => Country
4th column => Cost

Awk Command Examples

Printing specific columns

To print the 2nd and 3rd columns, execute the command below.
$ awk '{print $2 "\t" $3}' file.txt
Output
Awk Print Second And Third Column

Printing all lines in a file

If you wish to list all the lines and columns in a file, execute
$ awk ' {print $0}' file.txt
Output
Awk Print All Lines

Printing all lines that match a specific pattern

if you want to print lines that match a certain pattern, the syntax is as shown
$ awk '/variable_to_be_matched/ {print $0}' file.txt
For instance, to match all entries with the letter ‘o’, the syntax will be
$ awk '/o/ {print $0}' file.txt
Output
awk linux command matching all lines
To match all entries with the letter ‘e’
$ awk '/e/ {print $0}' file.txt
Output
Awk Matching Lines With E

Printing columns that match a specific pattern

When AWK locates a pattern match, the command will execute the whole record. You can change the default by issuing an instruction to display only certain fields.
For example:
$ awk '/a/ {print $3 "\t" $4}' file.txt
The above command prints the 3rd and 4th columns where the letter ‘a’ appears in either of the columns
Output
Awk Matching Column

Counting and Printing Matched Pattern

You can use AWK to count and print the number of lines for every pattern match. For example, the command below counts the number of instances a matching pattern appears
$ awk '/a/{++cnt} END {print "Count = ", cnt}' file.txt
Output
Count Columns Matching a pattern

Print Lines with More or less than a No. of Characters

AWK has a built-in length function that returns the length of the string. From the command $0 variable stores the entire line and in the absence of a body block, the default action is taken, i.e., the print action. Therefore, in our text file, if a line has more than 18 characters, then the comparison results true, and the line is printed as shown below.
$ awk 'length($0) > 20' file.txt
Output
Print Lines With More Or Less Characters

Saving output of AWK to a different file

If you wish to save the output of your results, use the > redirection operator. For example
$ awk '/a/ {print $3 "\t" $4}' file.txt > Output.txt
You can verify the results using the cat command as shown below
$ cat output.txt
Output
Awk Redirect Output

Conclusion

AWK is another simple programming script that you can use to manipulate text in documents or perform specific functions. The shared commands are a few or the many you are yet to know or come across.

Linux - AWK SCRIPTING: HOW TO DEFINE AWK VARIABLES

AWK variables: This is our ongoing tutorials on AWK scripting. As we mention earlier AWK is a full pledged language with all statements, arrays, control structures, functions etc. Today we will see how to define a variable in AWK and use it when it’s required. We already covered following AWK concepts


WHAT IS A VARIABLE?

A variable is defined as storage location to store some value in it so that we can use this in a program. Variables will protect us from varying values in the storage location. This will help us to avoid hardcode a value in to program where ever it’s used. We can define a variable at the start of program and use the variable across the program, if we want to change the value of it, we can change it where we define it and this value will be updated where ever we use that variable.

DEFINING A VARIABLE IN AWK

We can define variable in AWK where ever we require. Variables can be used for
Initializations for values
Arithmetic operations 
And many more.

For this concept we will use below db.txt file.
cat db.txt

Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122234 38 37
Edwin 253734 87 97 95
Dayan 24155 30 47

 

LETS LEARN AWK VARIABLES WITH EXAMPLES

Example1:  Add all values in column 3 and display for each addition from our db.txt file. Frist value should be first value in column3, second in the list should be first value + second value and so on.
awk ‘BEGIN{a=0}{a=a+$3;print a}’ db.txt
Output:
78
134
172
259
289

In the above example we defined a variable a and initialized to zero in the BEGIN block and did arithmetic operation in main block.
Example2: I don’t want above output, I just want to print a final value once the sum of all value in 3rd column. We can use END block for doing a final print instead of printing per iteration.
awk ‘BEGIN{a=0}{a=a+$3}END{print a}’ db.txt
Output:
289
Example3: Print all the lines which contain numbers greater than VAR1 in it’s column 4
awk ‘BEGIN{VAR1=57}(VAR1<$4){print $0}’ db.txt

Output:
Jones 2143 78 84 77
Gondrol 2321 56 58 45
Edwin 253734 87 97 95
These are simple examples to start with Varaiables. In our next post we will see how get inputs from user.

Linux - AWK SCRIPTING: 10 BEGIN AND END BLOCK EXAMPLES

BEGIN and END statements are help full in displaying information before and after executing actual AWK script.
BEGIN block Uses:
Declaring variables.
 
Initialization variables for doing increment/decrements operations in main AWK code.

Printing Headings/info before actual AWK code output.
 
END block Uses:
Printing final results, after doing operations in main AWK block.
 
Printing Completion/info after actual AWK code output.
 
AWK tool is mainly used for reporting some data in useful manner. With out these BEGIN and END blocks the output will be meaning less. In this post we will see different ways to use BEGIN and END blocks.
For this post the example file is db.txt which contains below data:
Jones 2143 78 84 77

Gondrol 2321 56 58 45

RinRao 2122234 38 37

Edwin 253734 87 97 95

Dayan 24155 30 47
What you get from above data? They are just names and followed by some numbers separated by spaces. If we can give some information at start of the file, such as what each column corresponding to etc as shown below
Names total PPT Doc xls

Jones 2143 78 84 77

Gondrol 2321 56 58 45

RinRao 2122234 38 37 0

Edwin 253734 87 97 95

Dayan 24155 30 47 0
This is more helpful to understand what actually this data is about. This type of output can be achieved by using BEGIN block. In this post we will see how to use BEGIN and END blocks with examples.

AWK BEGIN BLOCK

This is a block code which is executed before executing actual AWK script
Linuxnix-free-e-book
Syntax for BEGIN block is
awk 'BEGIN{awk initializing code}{actual AWK code}' filename.txt
 
Example1: Print a meaning full info before actual AWK output.
awk 'BEGIN{print "########################nThis is the output of filtered datan########################"}{print $0}' db.txt
 
Output:
##########################
This is the output of filtered data
##########################
Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122234 38 37
Edwin 253734 87 97 95
Dayan 24155 30 47
 
Example2: How about giving each column names along with data? We can name each column as Name, pass code,
awk 'BEGIN{print "NamesttotaltPPTtDoctxls"}{printf "%-st%dt%dt%dt%dn", $1,$2,$3,$4,$5}' db.txt
Output:
Names total  PPT Doc xls
Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122234 38 37 0
Edwin 253734 87 97 95
Dayan 24155 30 47 0
 
Example3: How about changing the output field separator to "|" we can do that by using OFS inbuilt variable in BEGIN block.
awk 'BEGIN{OFS="|"}{print $1,$2,$3,$4,$5}' db.txt
 
Output:
Jones|2143|78|84|77
Gondrol|2321|56|58|45
RinRao|2122234|38|37|
Edwin|253734|87|97|95
Dayan|24155|30|47|
 
Example4: How about converting /etc/passwd to above format? We can do that by defining input field separator "FS" to ":".
awk 'BEGIN{FS=":";OFS="|"; }{print $1,$2,$3,$4,$5,$6,$7}' /etc/passwd | head -5
 
Output:
root|x|0|0|root|/root|/bin/bash
daemon|x|1|1|daemon|/usr/sbin|/bin/sh
bin|x|2|2|bin|/bin|/bin/sh
sys|x|3|3|sys|/dev|/bin/sh
sync|x|4|65534|sync|/bin|/bin/sync
 
Note1: Make note that by default input field separator is either space or tab.
Note2: We can use either FS built-in variable or -F option to specify input field separator.
awk -F":" 'BEGIN{OFS="|"; }{print $1,$2,$3,$4,$5,$6,$7}' /etc/passwd | head -5
 
Output:
root|x|0|0|root|/root|/bin/bash
daemon|x|1|1|daemon|/usr/sbin|/bin/sh
bin|x|2|2|bin|/bin|/bin/sh
sys|x|3|3|sys|/dev|/bin/sh
sync|x|4|65534|sync|/bin|/bin/sync
 
Example5: We can use even BEGIN block to initialize user defined variables in it. I want to add my 3rd column for every iteration to the same value.
My 3rd column
78
56
21
87
55
 
I want to add these numbers and display every addition when it happen
awk 'BEGIN{s=0}{s=s+$3;print s}' db.txt
 
Output:
78
134
155
242
297
 
We initialized s in BEGIN block and incremented column 3 values in actual AWK code block.

AWK END BLOCK

This is piece of block which is executed after executing all the AWK code. This is the last AWK code going to execute.
Example6: Print some meaning full info after processing AWK code.
awk 'END{print "#########################/nCompleted printing filtered data/n########################"}{print $0}' db.txt
 
Output:
Jones 21 78 84 77
Gondrol 23 56 58 45
RinRao 25 21 38 37
Edwin 25 87 97 95
Dayan 24 55 30 47
#########################
Completed printing filtered data
#########################
 

COMBINING BEGIN AND END BLOCKS

Example7: Print some meaning full before and after AWK code execution.
awk 'BEGIN{print "##########################/nThis is the output of filtered data/n##########################"}{print $0}END{print "########################/nCompleted printing filterd data/n########################"}' db.txt
 
Output:
#########################
This is the output of filtered data
#########################
Jones 21 78 84 77
Gondrol 23 56 58 45
RinRao 25 21 38 37
Edwin 25 87 97 95
Dayan 24 55 30 47
########################
Completed printing filtered data
########################
 
Example8: How about printing headings for each column?
awk 'BEGIN{print "##########################nThis is the output of filtered datan###########################";print "NamesttotaltPPTtDoctxls"}{printf "%st%dt%dt%dt%dn", $1,$2,$3,$4,$5}END{print "###########################nCompleted printing filtered datan###########################"}' db.txt
 
Output:
###########################
This is the output of filtered data
###########################
Names total PPT Doc xls
Jones 21 78 84 77
Gondrol 23 56 58 45
RinRao 25 21 38 37
Edwin 25 87 97 95
Dayan 24 55 30 47
###########################
Completed printing filtered data
###########################
 
Example9: How to adding all the numbers in 4th column and print the total value at the end.
awk 'BEGIN{s=0}{s=s+$3}END{print s}' db.txt
 
Output:
297
 
There is a slight difference between Example 5 and this. We used END block to print the last sum instead of printing the sum for every iteration. In our next post we will see how to use AWK inbuilt variables  in detail.