Professional Documents
Culture Documents
There are many ways to do this. However the easiest way to display the first line of a file is using the
[head] command.
$> head -1 file.txt
No prize in guessing that if you specify [head -2] then it would print first 2 records of the file.
Another way can be by using [sed] command. [Sed] is a very powerful text editor which can be used
for various text manipulation purposes like this.
$> sed '2,$ d' file.txt
You may be wondering how does the above command work? OK, the 'd' parameter basically tells
[sed] to delete all the records from display output from line no. 2 to last line of the file (last line is
represented by $ symbol). Of course it does not actually delete those lines from the file, it just does
not display those lines in standard output screen. So you only see the remaining line which is the
first line.
If you want to remove line <m> to line <n> from a given file, you can accomplish the task in the
similar method shown above. Here is an example:
$> sed i '5,7 d' file.txt
The above command will delete line 5 to line 7 from the file file.txt
But not always you will know the number of lines present in the file (the file may be generated
dynamically, etc.) In that case there are many different ways to solve the problem. There are some
ways which are quite complex and fancy. But let's first do it in a way that we can understand easily and
remember easily. Here is how it goes:
$> tt=`wc -l file.txt | cut -f1 -d' '`;sed i "`expr $tt - 4`,$tt d" test
As you can see there are two commands. The first one (before the semi-colon) calculates the total
number of lines present in the file and stores it in a variable called tt. The second command (after
the semi-colon), uses the variable and works in the exact way as shows in the previous example.
$> echo A quick brown fox jumped over the lazy cat | cut f4 d' '
And it will print fox
If you connect to database in this method, the advantage is, you will be able to pass Unix side shell
variables value to the database. See below example
$>res=`sqlplus -s username/password@database_name
<<EOF
EXIT;
EOF`
$> echo $res
12
0.0
0.0
0.0
0.0
0.0
0.0