LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Software
User Name
Password
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.

Notices


Reply
  Search this Thread
Old 03-17-2008, 12:06 PM   #1
slaxative
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 12:09 PM.
 
Old 03-18-2008, 02:13 AM   #2
anotherlinuxuser
Member
 
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 > targetfile.new || 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 > targetfile.new
 
  


Reply



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 12 01-16-2023 10:21 AM
[SOLVED] sed: How to remove the end of a line? angel115 Programming 2 10-01-2007 10:29 AM
PHP Remove Line From Shoutcast Playlist File. Sed? windisch Programming 2 03-26-2007 08:52 PM
Remove string in sed twantrd Programming 7 09-13-2006 02:28 PM
sed question: remove decoration from each line Hivemind Linux - Software 1 01-18-2006 07:13 AM

LinuxQuestions.org > Forums > Linux Forums > Linux - Software

All times are GMT -5. The time now is 06:37 AM.

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