Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unix shell / SED oneliner to delete lines

Status
Not open for further replies.

pcdas

IS-IT--Management
Aug 7, 2001
5
IN
I want an one-liner to delete the TOP 5 lines or BOTTOM 5 lines from a text file. An early reply will be highly appreciated.
 
Try the following command to delete the first file lines.

Code:
sed -n '1,5d' inputfile > outputfile

Try the below command to delete last 5 lines
Code:
sed -e :a -e '$d;N;2,5ba' -e 'P;D' inputfile > outputfile
 
One liner in Korn Shell...
Code:
sed -n "6,$(($(( $(wc -l<inputfile) )) - 5))p" inputfile

A little more generalized...
Code:
# X is lines to remove from front and rear
X=5

sed -n "$((X+1)),$(($(( $(wc -l<inputfile) )) - $X))p" inputfile


 
A simpler way to delete the first 5 lines:

Code:
tail +6 inputfile > outputfile

And a not quite as simple way to delete the last 5:

Code:
head -n $(( $(wc -l<inputfile) - 5)) inputfile > outputfile

Sam, did you mean to include the extra set of $(( ))?

Annihilannic.
 
My sincere thanks to Dstxaix, Sam & Anihilannic for giving me different solutions. I tried all the different solutions and solved my problem. However, I liked the general solution provided by Sam ! You guys are fantastic !!
 
Hi Anni,

Yes, I did mean to include a second set of $(( )). It might not be needed, but I usually put that around anything that needs to be handled arithmetically.

Yup, you're right, this works fine...
Code:
# X is lines to remove from front and rear
X=5

sed -n "$((X+1)),$(( $(wc -l<inputfile) - $X))p" inputfile

 
And just for fun, a generalised awk solution:

Code:
awk -v l=5 'NR>l{print a[NR%l]}{a[NR%l]=$0}' inputfile



Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top