Sunday, August 15, 2010

UNIX - Print first and last line of file - sed, awk


Input file:

$ cat file.txt
50
57
52
60
52
90

Required output: Print the first and the last line of the above file.

50
90

Few alternatives using bash, sed and awk :

$ head -1 file.txt; tail -1 file.txt

$ sed -n '1p;$p' file.txt

$ awk 'NR==1; END{print}' file.txt

And a simple python program to achieve the same:

$ cat print-first-last-line.py
fp = open('file.txt','r')
data = fp.readlines()
fp.close()
print data[0],
print data[len(data)-1],

Related:

- Print next few lines after pattern is found using awk

6 comments:

Adithya Kiran said...

We can print the first and last line of the file using vim editor also.

1. Create a file called cmds.vim

2. Write down the following commands
:1p
:$p
:q

3. Now using vim, execute the below command.
# vim -es file.txt < cmds.vim

Form the manual pages of vim,
-e switch is for ex mode
-s switch for silent mode.

Done..!

Least used when you compare with sed, awk or head commands but the point is an editor can also does the same task!!!

Adam said...

Technically, you can shorten the Python script - use -1 as the index for the last line.

`print data[-1],`

Jadu Saikia said...

@Adithya Kiran : Thanks, the vi tip is very useful

@Adam, thanks for suggesting this, its helpful. thanks again.

Taufik Zukhan F said...

Hi Jadu,

Let i have text file test.txt

$cat text.txt

1111aaaa2222bbbb

For coloring the 1 same value with perl is like this

###let say we want coloring 'a'####

$tail text.txt | perl -pe 's/a/\e[1;33m$&\e[0m/g'

How we can coloring 2 or more different value with different color ?

Thanxs Before,

Regards




Anirudh said...

> Required output: Print the first
and the last line...

> $ sed -n '1p;$p' file.txt

Actually, the above would
print the 1st(=last) line twice
for single-line files :-(

This alleviates the issue:

sed -e '$q;1!d' file.txt

Anirudh said...

You can use some HTML tags, such as

© Jadu Saikia www.UNIXCL.com