Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed + remove string only in the last line of the file

Tags:

I use the following sed command to remove the line number string from file

sed -i s'/line number//g' file 

but what I need to change in sed syntax in order to remove the line number only if it exist in the last line of the file?

like image 664
lidia Avatar asked Aug 26 '10 14:08

lidia


People also ask

How do I remove the last line in Unix?

Deleting line using sed To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How do I remove the last line of a text file in Unix?

txt (if it ends with EOF , or \n and then EOF ), the number of lines in new_file. txt may be the same (as file. txt ) after this command (this happens when there is no \n ) - in any case, the contents of the last line is deleted.

How do you change the last line in a file with sed?

sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' : this will remove all the blank lines from end of the file. sed '$d' : this will remove the last line.


2 Answers

I'm not sure I fully understand your question, however this can help you :

sed -i '$ s/line number//g' file 

This will perform substitution only on last line (because of $), replacing line number by nothing.

man sed, section Addresses can help you understand how to apply sed commands on part of the text.

like image 176
Scharron Avatar answered Nov 11 '22 19:11

Scharron


For those who are on SunOS which is non-GNU, the following code will help:

sed '$d' tmp.dat > test.dat 
like image 30
Nasri Najib Avatar answered Nov 11 '22 18:11

Nasri Najib