Tuesday, September 2, 2014

Unix-Displaying the contents of a file on the screen

Displaying the contents of a file on the screen

clear (clear screen)

Before you start the next section, you may like to clear the terminal window of the previous commands so the output of the following commands can be clearly understood.
At the prompt, type
% clear
This will clear all text and leave you with the % prompt at the top of the window.

cat (concatenate)

The command cat can be used to display the contents of a file on the screen. Type:
% cat science.txt
As you can see, the file is longer than than the size of the window, so it scrolls past making it unreadable.

less

The command less writes the contents of a file onto the screen a page at a time. Type
% less science.txt
Press the [space-bar] if you want to see another page, and type [q] if you want to quit reading. As you can see, less is used in preference to catfor long files.

head

The head command writes the first ten lines of a file to the screen.
First clear the screen then type
% head science.txt
Then type
% head -5 science.txt
What difference did the -5 do to the head command?

tail

The tail command writes the last ten lines of a file to the screen.
Clear the screen and type
% tail science.txt
Q. How can you view the last 15 lines of the file?

  The head command in unix or linux system is used to print the first N lines from the file to the terminal. The syntax of head command is

head [options] [files]


The head command options are:

    c : Prints the first N bytes of file; With leading -, prints all but the last N bytes of the file.
    n : Prints first N lines; With leading – print all but the last N lines of each file.

Head Command Examples:
Create the following file in your linux or unix operating system for practicing the examples:

> cat example.txt
linux storage
ubuntu os
fedora

1. Display first 10 lines
By default, the head command prints the first 10 lines from a file.

> head example.txt

2. Display first N lines
Use the -n option to print the first n lines from a file. The following example prints the first 2 lines from the file:

> head -n2 example.txt
linux storage
ubuntu os

3. Skip last N lines
You can skip the last N lines from a file and print the remaining lines. The following example skips the last 2 lines and prints the remaining lines.

> head -n-2 example.txt
linux storage

4. Print the first n bytes.
use the -c option to print the first N bytes from the file. The following example prints the first 5 bytes from the file.

> head -c5 example.txt
linux

5. Skip printing last n bytes.
Use the leading “-”, to skip printing last N bytes.

> head -c-7 example.txt
linux storage
ubuntu os

6. Print line between M and N lines.
You can combine the head command with tail command to print lines between the line numbers M and N. The following command prints the lines between numbers 5 and 10.

> head -n10 filename | tail -5



No comments: