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

3 comments:
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!!!
Technically, you can shorten the Python script - use -1 as the index for the last line.
`print data[-1],`
@Adithya Kiran : Thanks, the vi tip is very useful
@Adam, thanks for suggesting this, its helpful. thanks again.
Post a Comment