Skip to content
Advertisement

How to remove only the last word from a file

I created the following Perl one-liner in order to remove a word from a file

This Perl also escapes special characters such as @ or $ or *, so every word that contains a special character will removed from the file.

How to change the Perl syntax in order to delete only the last matched word from a file and not all the words?

Example

JavaScript
JavaScript

expected results

JavaScript

another example

when – export REPLACE_NAME=”mark@$!”

JavaScript

expected results

JavaScript

Advertisement

Answer

Use Tie::File to make this easier.

JavaScript

Update: Rewriting as a program in order to explain it.

JavaScript

Update: So now you’ve changed you requirements spec. You want to remove the last occurrence of the string, which is not necessarily on the last line of the file.

Honestly, I think you’ve moved past the kind of task that I’d write in command-line switches. It’d write a separate program that looks something like this:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement