In: Computer Science
The awk commands to print the first and third words (with a
space between) from each line of the input that has the substring
'cat' in the second word (assume all lines have at least three
words). Note, words are fields in this case. Your output should be
a copy of each input line with the substring 'cat' in the second
word and also, with just the first and third words printed. A
series of comments that fully describes your awk commands,
including a description of the purpose of each function call, and
the arguments to each function.
using the command awk -f quest1.awk input.txt where 'input.txt' is
the input file..
Input File(input.txt):
So there are 5 lines with three words separated by space. In which, two of them contain the substring "CAT" in the second word.
Program Output:
Since the Line2 , line4 and line5 only contain the substring CAT in the second word, I displayed the 1st and 3rd words for each of them as suggested by you. Please let me know if you need more help or clarification needed on this task. Also request you to hit the like button if you are satisfied with my answer.
Program code with comments(quest.awk):
#!/usr/bin/awk -f
#Program execution starts from here
BEGIN {
# Reading each line from the input file using getline built-in
function and storing the record value to a variable called 'line'
with the help of while loop
# Here the value of ARGN[1] = input.txt
while (( getline line <ARGV[1]) >0)
{
# Splitting the current line with space and storing it to an array
named 'a'
split(line,a," ");
#Checking whether the second word in the array contains a
substring named "cat"
if (a[2]~/cat/)
{
# If there is a substring named 'cat' is present, then print the
first and third words for the current line
print ""a[1]" "a[3]""
}
}
}
akhil@akhil-VirtualBox:-/todays cat input.txt line1 dogs birds line2 cats animals line3 animals birds line4 Scats dogs line5 10cat animals
akhil akhil-VirtualBox:-/todays awk -f ./questi.awk input.txt Hine2 animals line4 dogs line5 animals