LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Trying to use sed to remove last line if it contains a certain string. (https://www.linuxquestions.org/questions/linux-software-2/trying-to-use-sed-to-remove-last-line-if-it-contains-a-certain-string-628710/)

slaxative 03-17-2008 12:06 PM

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.

anotherlinuxuser 03-18-2008 02:13 AM

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


All times are GMT -5. The time now is 06:47 PM.