Monday, 21 December 2015

How To Use Head Command In Unix/Linux

In this article we will see how head command works and its real time practical example.

File1:abc.txt
10001|A1|TRANS|Y|10000
10002|A2|MED|Y|20000
10003|A3|FIN|N|10000
10004|A4|HR|Y|20000
10005|A5|CSR|N|50000
10006|A6|TRANS|Y|30000
10007|A7|FIN|N|40000

File2: xyz.txt
20001|B1|TRANS|Y|10000
20002|B2|MED|Y|20000
20003|B3|FIN|N|10000
20004|B4|HR|Y|20000
20005|B5|CSR|N|50000

How to read first 3 line of a file
$ head -n 3 abc.txt

[OR]

$ head -3 abc.txt

Output: Will display the first 3 lines of the file abc.txt
10001|A1|TRANS|Y|10000
10002|A2|MED|Y|20000
10003|A3|FIN|N|10000

How to ignore last 3 line of a file 
$ head -n -3 abc.txt

Output: Will display the all the lines except last 3 lines from the file abc.txt
10001|A1|TRANS|Y|10000
10002|A2|MED|Y|20000
10003|A3|FIN|N|10000
10004|A4|HR|Y|20000

Default head will display first 10 lines of a file.
$ head abc.txt

Output: Has displayed complete file as it has less than 10 lines.
10001|A1|TRANS|Y|10000
10002|A2|MED|Y|20000
10003|A3|FIN|N|10000
10004|A4|HR|Y|20000
10005|A5|CSR|N|50000
10006|A6|TRANS|Y|30000
10007|A7|FIN|N|40000

How to see lines from multiple files
$ head abc.txt xyz.txt

Output: Will display the first ten lines of both abc.txt and xyz.txt, with a header before each that indicates the file name.

How display the first 3 lines from multiple table
$ head -n 3 abc.txt xyz.txt

Output:Will display the first 3 line from both the file.
==> abc.txt <==
10001|A1|TRANS|Y|10000
10002|A2|MED|Y|20000
10003|A3|FIN|N|10000

==> xyz.txt <==
20001|B1|TRANS|Y|10000
20002|B2|MED|Y|20000
20003|B3|FIN|N|10000

How to see the first 4 lines of .txt file in the directory
$ head -n 4 *.txt

Output: Display the first four lines of every .txt file in the working directory
==> abc.txt <==
10001|A1|TRANS|Y|10000
10002|A2|MED|Y|20000
10003|A3|FIN|N|10000
10004|A4|HR|Y|20000

==> xyz.txt <==
20001|B1|TRANS|Y|10000
20002|B2|MED|Y|20000
20003|B3|FIN|N|10000
20004|B4|HR|Y|20000

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...