954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to delete last three lines in file

Hi,

I wish to delete the last three lines of a file iteratively. I tried this in unix shell scripting but it is not working..

lines=$(wc -l < s27.cnf)
target=$((lines-2))
sed '$target,$lines d' s27.cnf > f2.cnf
mv f2.cnf s27.cnf

I am getting an error "sed: 1: "$target,$lines d": undefined label 'arget,$lines d'
So was not sure what to use.

I would appreciate help on this.

guest7
Junior Poster
109 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

Single quotes disable substitution, so perhaps
sed "$target,$lines d" s27.cnf > f2.cnf
sed $target','$lines' d' s27.cnf > f2.cnf

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Hey there,

You can also do it this way

sed -e :a -e '$d;N;2,3ba' -e 'P;D' s27.cnf >f2.cnf

Just change the 3 to hower many lines you want to delete from the bottom

Best wishes,

Mike

eggi
Posting Pro in Training
400 posts since Oct 2007
Reputation Points: 102
Solved Threads: 47
 

Thanks...it worked...

I appreciate the help

guest7
Junior Poster
109 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

Your welcome, of course :)

Best wishes,

Mike

eggi
Posting Pro in Training
400 posts since Oct 2007
Reputation Points: 102
Solved Threads: 47
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You