Linux commands : awk, sed, grep, expect


awk command treats the spaces as a delimiter for fields by default.

awk 'command' <file-name>
awk '{print}' awkcommand.txt
awk '{print $1}' awkcommand.txt # it will show the first field

here we put $1 to get the first field of each line.

remember $0 represents the field type so it will print the whole file.

we also can select multiple fields like : $1,$3


echo "here is an example of awk command" | awk '{print $6,$7}'

awk '{print $NF}' awkcommand.txt

$NF stands for number of fields. Here it will print the last field in the file.

sometimes the delimiter is not a space " ", At that moment we can define what delimiter we want to use
for example our /etc/passwd file

Here we can see the : can be delimiter. We can define the delimiter like -F ':'

awk -F':' '{print $6}' /etc/passwd

How can i search a single word and multiple word in a file using awk ?

awk '/john/{print $0}' sample2.txt
awk '/john|alex/{print $0}' sample2.txt

multiple words:

How can you print the line number at the beginning of each line ?

awk '{print NR, $0}' sample2.txt # NR denotes the number of rows

How to print a specific line from the text file ?

awk 'NR==5 {print $0}' sample2.txt
awk 'NR==5 {print NR, $0}' sample2.txt #here NR prints the line number also

How to get the line number of empty line ?

in empty lines the field number is zero, so we can put the condition for it as NF==0

awk 'NF==0 {print NR, $0}' sample2.txt

Find if a particular alphabet or word is present in a specific column and print it ?

awk '$3 ~ /p/ {print $0}' sample2.txt
awk '$2 ~ /john/ {print $0}' sample2.txt