Visit Jeremy's Blog.
Go Back > Forums > Linux Forums > Linux - Software
User Name
Linux - Software This forum is for Software issues.
Having a problem installing a new program? Want to know which application is best for the job? Post your question in this forum.


  Search this Thread
Old 03-17-2008, 01:06 PM   #1
LQ Newbie
Registered: Nov 2007
Posts: 3

Rep: Reputation: 0
Trying to use sed to remove last line if it contains a certain string.

I'm trying to figure out how to utilize "sed" to remove the last instance of a certain string in a file. Not on every line, just the last line containing certain text.

Last edited by slaxative; 03-17-2008 at 01:09 PM.
Old 03-18-2008, 03:13 AM   #2
Registered: Jan 2007
Location: Alberta Canada
Distribution: Fedora/Redhat/CentOS
Posts: 70

Rep: Reputation: 19
Here's one way:

Enter these 2 command lines:

# set var lastline to line number of last instance of string.
lastline=`grep -n "target string" targetfile | tail -1 | cut -d':' -f1`

# use sed to delete that line, if a value for lastline was found.
[ "$lastline" != "" ] && sed -e $lastline,${lastline}d targetfile > || echo "string not found"

Note that sed cannot write its output to the input file name.
This could also be done on one line, but that would require reading the input file a total of 3 times instead of twice and doesn't allow you to check if the string was found before doing the sed:
sed -e `grep -n "target string" targetfile | tail -1 | cut -d':' -f1`,`grep -n "target string" targetfile | tail -1 \
| cut -d':' -f1`d targetfile >


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
SED - remove last four characters from string 3saul Linux - Software 10 12-04-2018 01:24 PM
[SOLVED] sed: How to remove the end of a line? angel115 Programming 2 10-01-2007 11:29 AM
PHP Remove Line From Shoutcast Playlist File. Sed? windisch Programming 2 03-26-2007 09:52 PM
Remove string in sed twantrd Programming 7 09-13-2006 03:28 PM
sed question: remove decoration from each line Hivemind Linux - Software 1 01-18-2006 08:13 AM > Forums > Linux Forums > Linux - Software

All times are GMT -5. The time now is 09:21 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration