Although Paul answers correctly, I would like to point out that there is another way to look at your problem. Your question indicates that the line ends with "YES" or "NO". So one more thing you could do is split the line and print the last element if it matches โYESโ or โNOโ:
perl -lape'$_=$F[-1] if $F[-1]=~m/^(?:YES|NO)$/'
In your example, all lines ended with YES or NO. If this is true for all lines in your input, this can be simplified to:
perl -lape'$_=$F[-1]'
A brief explanation of the Perl command line flags used (you can also read this in perloc perlrun):
- -l is used to automatically split input lines and add "\ n" when printing. A.
- -a automatically splits the input string in a space into an @F array when used with "-n" or "-p".
- -p creates a loop that runs along the lines of the given input file / s and does a โprintโ at the end after running your code.
- -e is, of course, a flag for providing code on the command line
So basically command line flags do most of the work. The only thing I need to do is assign $ F [-1] (the last element of the line) to $ _, which will be printed using "-p".
My goal was not to play Perl Golf and show you a shorter way to answer your question, instead I'm trying to point out that just thinking about a problem from a slightly different angle can show you different ways to solve it, which may be better / more elegant. Therefore, please do not focus on which solution is shorter, but think about how different people attacked even this simple problem from different directions and how you can do the same.
Another point, you wrote "I want to replace strings." If you meant a replacement in the input file, the command line flag "-i" (replace in place) is your friend:
perl -lapi.bak -e'$_=$F[-1]'
source share