My question is about finding and saving the last word of each line.
I have multiple lines. This information is saved in a .txt
file. Thus, I am required to build a CMD script that can scan through the txt file, find the last word of each line and save it to a new .txt
document. The delimiters here will be the space.
For example:
It's a very small window<34>. The small birds were singing softly. There are three small rooms up stairs (4) The house has but two small second story bedrooms.
The result I would like to see saved in a separate txt document needs to look like the following:
window<34>. softly. (4) bedrooms.
I have tried many options and methods but unfortunately no luck.
This pure Batch method correctly process all characters, but it is limited in the number of words per line (26 in this version), although such a limit may be increased via the usual tricks.
Squashman's answer can fail if the file contains quotes and poison characters.
It is possible to write a pure batch solution that reliably does the job, regardless of content.
But I would never use a pure batch solution. Instead I would use JREPL.BAT - a hybrid batch/Jscript utility that efficiently performs regular expression search and replace on text. It isn't pure batch, but it is pure script that runs natively on any Windows machine from XP onward - no 3rd party .exe file required.
One nice thing about both solutions is that they give the correct result even if there are spaces after the last "word". And they don't print anything if the line does not contain any "word"
Give this a try. It uses a neat trick with the
SET
command. You can get a high level overview of this technique at dostips.com.