Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete last word in each line in bash

Tags:

regex

bash

sed

I am trying to go through a file, and delete the last word in each line. Currently, I am using the command

sed 's/^*\n//' old.txt > new.txt

but it is coming out that old.txt is the same as new.txt. Thanks for any help, and let me know if I can clarify the question. Also, in order to define 'word' I am just using spaces.

like image 838
Michael Rauh Avatar asked Apr 18 '12 23:04

Michael Rauh


2 Answers

Try the following. \w* matches the last word inside of the file and $ anchors the search to the end of the line.

sed s/'\w*$'// old.txt > new.txt

The reason that old.txt is coming out as new.txt is likely because your regular expression ^*\n is not matching any lines in old.txt.

like image 119
David Z. Avatar answered Sep 25 '22 16:09

David Z.


The following is an inline edit. PRIOR TO RUNNING ANYTHING PLEASE BACKUP YOUR FILE.

sed -i 's/[[:alnum:]]*$//' /yourfile

If you are working on OS X, you may want to try the following

sed -i '' 's/[[:alnum:]]*$//' /yourfile

If you are not interested in writing directly back to the original file, but would like the output to be printed.

sed 's/[[:alnum:]]*$//' /yourfile
like image 30
E1Suave Avatar answered Sep 21 '22 16:09

E1Suave