3

Create a shell script which prints the line contents when the line number is divisible by 3 from an input file. Assume the first line is line 1. At the end of the script, if the total number of lines divisible by 3 is greater than 10, print “big”. Otherwise, print “small”.

So far this is what I have

echo $1
file=$1

awk 'NR%2==0' $file

count=$(wc -l $file | grep -o "^[0-9]")
if [ $count -gt 20 ]
then
   printf "\nbig\n"
else
   printf "\nsmall\n"
fi
3

Here is an awk solution. I have deliberately kept it simple.

$ cat awkfile
BEGIN {
   count = 0;
}

NR % 3 == 0 {
   count++
   print
}

END {
   print ""
   if (count > 10)
      print "big"
   else
      print "small"
}

Invoke as:

$ awk -f awkfile infile
1

This Perl one-liner does the job:

perl -ane 'next if $.%3;$c++;print}{print($c>10?"big\n":"small\n")' file

Explanation:

perl -ane           # invoque perl compiler

'
  next if $.%3;     # next record if num_line modulo 3 is different than zero
  $c++;             # increment counter
  print             # print current line
  }{                # end of process
  print(            # print
    $c>10?          # if counter > 10
    "big\n"             # print "big" and newline
    :               # else
    "small\n"           # print "small" and newline
  )                 # end print
' 

file                # file to be processed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.