Linux Bash Coding Exercise – Get the Tenth Line of File


How would you print just the 10th line of a file?

For example, assume that file.txt has the following content:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Your script should output the tenth line, which is:

Line 10

The OJ Online Judge now supports the Shell puzzles so you can submit your solution here: https://leetcode.com/problems/tenth-line/

Tail and Head

tail and head are two frequently-used and popular commands that prints out the last few or first few lines of file respectively. So the easiest solution would be:

1
tail -n +10 file.txt | head -1
tail -n +10 file.txt | head -1

Note, the +10 here (with plus sign) means the tail command starts with the 10th line of file file.txt and the output is piped redirected to head which extracts the first line, which is exactly the 10-th line of the file.

Alternatively, you can use command cat f – g to output file f‘s content and then g’s. So the following command adds 10 extra empty lines to the output that ensures that head (default gets first ten lines) returns reasonable stuffs. tail -n 1 returns the last line of previous output.

1
2
3
4
5
6
7
8
9
10
echo "
 
 
 
 
 
 
 
 
" | cat file.txt - | head | tail -n 1
echo "








" | cat file.txt - | head | tail -n 1

Note that if file.txt does not contain ten or more lines, the head -10 file.txt | tail -1 returns incorrect result, but you can easily fix this:

1
2
3
4
5
NR=`cat file.txt | wc -l`
 
if [ $NR -ge 10 ]; then
    head -10 file.txt | tail -1  
fi
NR=`cat file.txt | wc -l`

if [ $NR -ge 10 ]; then
    head -10 file.txt | tail -1  
fi

AWK

AWK is a powerful tool (programming) that deals with text.

The following command prints the line if the variable (NR = Number of Rows) equals to 10.

1
awk '{if(NR==10) print $0}' file.txt
awk '{if(NR==10) print $0}' file.txt

Even simpler solution exists:

1
awk "NR==10" file.txt
awk "NR==10" file.txt

SED

sed is a stream editor under command line. It executes the instruction on the text stream and the following prints the 10-th line using sed.

1
sed -n '10p' file.txt
sed -n '10p' file.txt

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
477 words
Last Post: C++ and Python to Compute the Pascal Triangle
Next Post: SQL Coding Exercise - Rising Temperature

The Permanent URL is: Linux Bash Coding Exercise – Get the Tenth Line of File

Leave a Reply