How can I take the last line from a log file and extract just the filename?

5,570

How can I take the last line from a log file and extract just the filename?

Use the following batch file (test.cmd):

@echo off
setlocal enabledelayedexpansion
for /f tokens^=2^ delims^=^" %%a in (file.log) do (
  set "lastLine=%%~na"
  )
echo %lastLine%>test.txt
endlocal

Example:

F:\test>type file.log
Opening track for playback: "D:\Music\Mellow Vibe ? lofi study mix.m4a"
Opening track for playback: "D:\Music\Logic - Overnight.m4a"

F:\test>test
F:\test>type test.txt
Logic - Overnight

F:\test>

Further Reading

Share:
5,570

Related videos on Youtube

user1166618
Author by

user1166618

Updated on September 18, 2022

Comments

  • user1166618
    user1166618 almost 2 years

    I've been trying to write code in batch (powershell is also fine) to take the last line from a log file and remove some text from it, here's the logfile I'm trying to do it from:

    Opening track for playback: "D:\Music\Mellow Vibe ● lofi study mix.m4a"
    Opening track for playback: "D:\Music\Logic - Overnight.m4a"
    

    It's a log from a music player program that will output whatever song is playing like this, each of the songs have various titles and I'm trying to remove the string

    Opening track for playback: "D:\Music

    at the beginning of the text and the string

    .m4a"

    at the end of the text. All of the files have different names but they all are in the same locations and will always begin and end the same, the only difference being the actual song/file name.

    Here's the code I have, it's fairly basic code that will only fetch the last line from the log file, I'm not sure how to go about removing the text from the beginning/end of it, I would also like it to auto-update when a new song (string) is appended to the [log] file, if possible:

    @echo off
    for /F "delims=" %%a in (file.log) do (set "lastLine=%%a")
    echo %lastLine%>test.txt
    pause
    
    • Keith Miller
      Keith Miller about 4 years
      Why do you keep creating new questions for the same thing??? You've been given mulitple solutions & refuse to engage those trying to help!
    • Keith Miller
      Keith Miller about 4 years
      Does this answer your question? Need assistance with writing a batch script
    • Lee_Dailey
      Lee_Dailey about 4 years
      please ... do not spam the site with variants of one Question. [frown]
    • Keith Miller
      Keith Miller about 4 years
      So, is PowerShell an option? If not, why not? Batch & cmd will be obsolete at some point. There's a reason it's now the default console for the PowerUser Menu & directory context menus. If you want to learn & have fun with scripting & automation, PowerShell is the way to go.