Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a script named print_lines.sh that uses head and tail together to print ou

ID: 3665103 • Letter: W

Question

write a script named print_lines.sh that uses head and tail together to print out a specific set of lines from a file. The script should take three arguments: the line number to start at, the line number to stop at, and the file to use. Here's an example run:

------------------------------------------------------------------------------------------------------------------------

[user@localhost ~]$ print_lines.sh 7 10 /etc/passwd

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

[user@localhost ~]$

-------------------------------------------------------------------------------------------------------------------

In this example, the script prints line 7 through 10 (inclusive) of the /etc/passwd file. Your script must do error checking. Specifically, you need to check all the following things:

You get the right number of arguments (3).

The file specified exists and is a normal file.

The first line number specified is less than or equal to the last line number specified.

The actual number of lines in the file is greater than the last line to be printed.

If any of those conditions are not true, you should print an appropriate error message to the user and stop. If they are all met, then you'll need to do a bit of arithmetic and use head and tail together to print out only the lines requested.

Explanation / Answer

filename=$1
firstline=$2
lastline=$3

sed -ne "${firstline},${lastline}p;${lastline}q" < ${filename}


or
To avoid external utilities

filename=$1
firstline=$2
lastline=$3
i=0
exec <${filename} # redirect file into our stdin
while read ; do # read each line into REPLY variable
i=$(( $i + 1 )) # maintain line count
if [ "$i" -ge "${firstline}" ] ; then
if [ "$i" -gt "${lastline}" ] ; then
break
else
echo "${REPLY}"
fi
fi
done