Learning BASH: Text Processing - HEAD & TAIL

BASH continues to surprise me with it's amazing collection of simple, yet extremely useful commands. They can give you a huge boost in speed and control while working. No doubt bash along with editors like VIM are the developer's favorite combinations. Gradually , you will feel the invention of mouse as a waste since you can pretty much control everything with just your keyboard.

Today we continue with more commands that are related to Text Processing.

HEAD & TAIL command


These commands are used to get contents of a file starting from the top and bottom. Unlike the CAT command that displays the whole content of a file, these command gives you control over how much you want to see.

syntax: HEAD filename | TAIL filename

Note: By default, HEAD | TAIL shows 1st/last 10 lines of a file.

Lets say I have a text file like this.

$ cat numbers.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Let's run head command without any arguments other than the filename.

$ head numbers.txt
1
2
3
4
5
6
7
8
9
10

Problem: Display first 5 lines of the file provided.

$ head numbers.txt -n 5
1
2
3
4
5

$ tail numbers.txt -n 5
16
17
18
19
20


The -n argument lets us specify the number of lines I want to see/grab , starting from the first line.

Problem: Display the first 20 characters of a file/some text line.


$ echo "This is a test line with many characters" | head -c 12
This is a te

$ echo "This is a test line with many characters" | tail -c 12
 characters


Here, the -c argument is for character count. As the bash help says,

  -c, --bytes=[-]NUM       print the first NUM bytes of each file with the leading '-', print all but the
                                         last NUM bytes of each file


Note: HEAD/TAIL commands do not accept a range. So you can't display lines starting from n1 to n2. say 5-10th line. You can do that, but using a mixture of tail and head command. We will see that later.

TIP:

One of the most popular use of the tail command is to monitor changes to a file. Example a log file that logs each activity in a software or a website.

$ tail -f log.txt

The -f is for file input.

Problem: Display the lines from the given file between line 10 and 15.

Solution: So head gives us lines from first line i.e 1 to n . And tail gives us n lines , counting from the bottom . Our answer is expected as 11,12,13,14 as I said , I want numbers IN BETWEEN 10 and 15.

In plain words, this might be our plan.


  • First we get us the all numbers till (15 - 1). i.e 1 to 14. 
  • Then we remove 1 to 10 from this and the rest is our answer. In pictures, I can put it like this.






$ head numbers.txt -n 15 | tail -n 5
11
12
13
14
15

Popular posts from this blog

Why should you visit Kashmir sooner?

How to run a Python program over the internet?

CNTLM in Office