2

Como fazer o script funcionar?

Basicamente ele lê nomes que contem em arquivos.tag Ex: file1.tag, file2.tag... após ler esses nomes ele procura pelo nome em um ou outro arquivo.txt que contem as informações todas do nome procurado, por sua vez ele gera um arquivo Favorites.txt puxando todas as informações do arquivo.txt que ele leu, toda vez incrementando na próxima linha, o problema que eu estou tendo é que quando ele tenta ler nomes que contem espaços ele da um erro e não grava no arquivo favoritos.txt, segue abaixo o código e o erro que ocorre, se alguém puder me ajudar ficaria grato.

Obs. 1.: no arquivo Arcade.tag o nome esta assim: 64street ai ele procura em Arcade.txt pelo nome e copia para o arquivo Favoritos.txt assim: "64street;64th. Street - A Detective Story (World);Arcade;;1991;C.P. Brain;Briga de rua-Luta / 2.5D-Luta;1-2;;;;;;;;0.5;;;;;" que seria o formato correto.

Obs. 2.: Ja no próximo arquivo Sega Genesis.tag o nome esta assim: Duke Nukem 3D (Brazil) nesse caso deveria copiar isso Duke Nukem 3D (Brazil);10 Super Jogos;Sega Genesis;;2002;Epyx;Compilação-Estratégia-Esporte;8+;;;;;;;;0.8; mais acontece o erro e não copia.

Erro:

==========================================================
    AM favorites romlist generator script for Windows
==========================================================
- Backing up old Favorites.txt file
- Gathering list of favorites (tag files)
- Processing tag file: Arcade.tag
- Searching rom list: Arcade.txt for rom: 64street
- Favorites.txt romlist generated. 1 romlists read, 1 favorites written to disk
- Done

Add a display in Attract Mode and set its romlist to the newly created Favorites.txt
- Processing tag file: Sega Genesis.tag
- Searching rom list: Sega Genesis.txt for rom: Duke Nukem 3D (Brazil)

>FINDSTR: não foi possível abrir Nukem
>FINDSTR: não foi possível abrir 3D
>FINDSTR: não foi possível abrir (Brazil)
>FINDSTR: não foi possível abrir Nukem
>FINDSTR: não foi possível abrir 3D
>FINDSTR: não foi possível abrir (Brazil)
>FINDSTR: não foi possível abrir Nukem

Código Usado:

@echo off 
setlocal EnableDelayedExpansion EnableExtensions 
rem     ================================================================================
rem     This script basically does the same thing as DM's favorites romlist generator
rem     but on Windows [Shouts to him for the pi version ;)].
rem     How it works:
rem     It grabs all the (tagged) favorites from every tag file, searches for them
rem     through all the romlists, then generates a romlist called Favorites.txt
rem     Written by Steve Sherrod, 05/20/17, as part of project HyperPie Expanded
rem     ================================================================================

rem     Default path (on windows). This should point to your attract modes romlists dir
cd "D:\AM-2.6.1\romlists\"

echo ==========================================================
echo     AM favorites romlist generator script for Windows
echo ==========================================================

echo - Backing up old Favorites.txt file

rem     remove the old Favorites.txt and create the backup
if exist Favorites.txt (
    move /y Favorites.txt Favorites.txt.backup
)

echo - Gathering list of favorites (tag files)

set /a numfavorites=0
set /a romlist=0

rem     loop through each tag file
for %%f in (*.tag) do (
    echo - Processing tag file: %%~nf.tag
    set /a numtagfiles=numtagfiles+1
    
    rem     loop through favorites stored in tag file
    for /f "tokens=*" %%a in ('type "%%~nf.tag"') do (
    
        set /a numfavorites=numfavorites+1
        set favorite=%%a

        echo - Searching rom list: %%~nf.txt for rom: %%a
        
        rem     loop through each rom file and parse favorited (tagged) roms
        for /f "tokens=*" %%s in ('type "%%~nf.txt"') do (
            set /a romlist=romlist+1
            set str=%%s
            rem     Search current line (for current favorite substring) and if found, append it to Favorites.txt
            echo."!str!" | findstr /c:%%a>nul && (
                echo "!str!">>"Favorites.txt"
            )
        )
    )

echo - Favorites.txt romlist generated. !numtagfiles! romlists read, !numfavorites! favorites written to disk
echo - Done
echo.
echo Add a display in Attract Mode and set its romlist to the newly created Favorites.txt
)

3
  • 1
    Nessa parte: echo."!str!" | findstr /c:%%a>nul && ( tenta colocar uma aspas em %%a -> "%%a" 17/01/2021 às 13:35
  • sei que isso não responde a pergunta mas, pq não substituir esse batch por um script power shell que tem milhares de funções a mais e deixaria esse trabalho bem mais fácil? 17/01/2021 às 16:09
  • Show!!! vc achou o problema na veia, muito obrigado pela ajuda, sobre o poweshell não tenho noção dele, poderia por gentileza me dar um exemplo? 19/01/2021 às 18:05

1 Resposta 1

1
@echo off 

setlocal EnableDelayedExpansion 
set/a "_tag=0,_num=0" && pushd "D:\AM-2.6.1\ROMlists" 

echo==========================================================
echo=    AM Favorites ROMlist Generator Script for Windows     
echo==========================================================

if not exist .\favorites.txt (
     set/p "'= - Cretating .\Favorites.txt File.."<nul & echo\
   ) else 2>nul (set/p "'= - Backing up your old Favorites.txt: "<nul
     move/y .\Favorites.txt .\Favorites.txt.backup >nul && echo\Done^!!)
      
echo/- Gathering list of your Favorites: Tags-Files
for %%G in (*.tag)do set/a "_tag+=1" && for /f useback^delims^= %%i in (`
more "%%~G"`)do set/p "'=- ROM Found in File %%~nxG: %%~i"<nul & echo= & ( 
     <con: find "%%~i;" <"%%~nG.txt" >>".\Favorites.txt" && set/a "_num+=1")

set/a "_num+=10000,_tag+=10000" && <con: call echo/- Romlist Files [tag=txt]: !_tag:~-3!
echo/- Favorites added to Disc: !_num:~-3! & echo/- ROMlist .\Favorites.txt: New && popd
endlocal & echo/- is Done!.. & timeout 3|findstr /ec:\.\Favorites\.txt "%~f0" & goto:EOF

========================================================================================
- Add a display in Attract Mode and set its ROMlist to the newly created .\Favorites.txt
========================================================================================
  This script basically does the same thing as DM's Favorites ROMlist generator but 
  on Windows [ Shouts to him for the pi version d;) ].
                                                         
  How it works:
  It grabs all the (tagged) favorites from every tag file, searches for them through
  all the ROMlists, then generates a ROMlist called Favorites.txt Written by Steve 
  Sherrod, 05/20/17, as part of project HyperPie Expanded
========================================================================================
  • Saída:
=========================================================
    AM Favorites ROMlist Generator Script for Windows
=========================================================
- Backing up your old Favorites.txt: Done
- Gathering list of your Favorites: Tags-Files
- ROM Found in File Arcade.tag: 64street
- ROM Found in File Arcade.tag: mslug
- ROM Found in File Arcade.tag: 40love
- ROM Found in File Sega Genesis.tag: blkdrgon
- ROM Found in File Sega Genesis.tag: Duke Nukem 3D (Brazil)
- ROM Found in File Sega Genesis.tag: afighter
- ROM Found in File Sega Genesis.tag: airduel
- Romlist Files [tag=txt]: 002
- Favorites added to Disc: 007
- ROMlist .\Favorites.txt: New
- is Done!..
- Add a display in Attract Mode and set its ROMlist to the newly created .\Favorites.txt
  • Favorites.txt:
64street;64th. Street - A Detective Story (World) (1991);6.91
mslug;Metal Slug - Super Vehicle-001 (1996);9.18
40love;Forty-Love (1984);0.00
blkdrgon;Black Dragon (Japan) (1987);9.40782122909
Duke Nukem 3D (Brazil);10 Super Jogos;Sega Genesis;;2002;Epyx;Compilaçao-Estratégia-Esporte;8+;;;;;;;;0.8;
afighter;Action Fighter (FD1089A 317-0018) (1986);7.00
airduel;Air Duel (Japan) (1990);6.74

1. Use /D com o cd /D, isso faz o cmd.exe|CHDIR entrar na pasta e no /Drive apontado por argumento, o que não vai ocorrer sem adicionar o /D quando é executado apontando para drive diferente do atual.

cd /d "D:\AM-2.6.1\ROMlists"

Obs.: Pode também substituir cd /d pelo pushd, que altera a ordem na fila de pastas para busca dos seus comandos entrando na pasta passada pelo argumento já colocando a pasta atual para a primeira na fila/pilha, e também salvando o Drive\Pasta onde foi originalmente executado para retornar quando executar com popd.

pushd "D:\AM-2.6.1\ROMlists" 
          ...    ...
       ...seus códigos...
          ...    ...
popd

2. O comando set /a pode ser usado para definir múltiplas variáveis já atribuindo os seus valores passados após o símbolo de igual, apenas utilizando como delimitadores, um espaço mais uma vírgula (ou apenas uma vírgula), ficando o seu comando para definir os valores de _num_favorites=0 e de _ROMlist=0:

set "variável_1=valor_1, variável_2=valor_2, variável_3=valor_3"

rem :: Ou sem o espaço

set "variável_1=valor_1,variável_2=valor_2,variável_3=valor_3"

Obs.: A variável romlist é delcarada set /a romlist=0 mas não figura em uso no seu código postado...

3. O autor original do código usou um if exist favorites.txt() sem um else(), ignorando (por alguma razão), a possível inexistência do arquivo ou uma ação de exclusão do arquivo pelo usuário, o que tornar falsa a mensagem Backing up old favorites.txt file presente na primeira execução, ou para quando o usuário resolver apagar esse arquivo.

4. O comando set /a "variavel=variavel + 1" pode ser substituído por set /a "variável+=1" para aplicar o incremento de sua variável (para decremento é só inverter o sinal set /a "variavel-=1").

5. Os loopings For (1x) e For /F (2x) utilizados no bat original são muito lentos, eles vão pegar um MesmoNomeArquivo.TAG e comparar linha por linha com cada linha de MesmoNomeArquivo.TXT.

6. Você pode alterar o loop para procurar no outro arquivo (todo e de uma vez):

listar o linha por linha do arquivo.tag 
... for /f "usebackq delims=" %%i in (`more "%%~G"`)do (
    ...
    procurar a linha do arquivo.tag no arquivo.txt de uma vez já gravando o resultado
    find "%%~i;" <"%%~nG.txt">>".\Favorites.txt"
    ...

Obs.: Mas perceba que isso acelara o processamento entre os dois arquivos, se o MesmoNomeArquivo.TAG tiver 10 linhas e o MesmoNomeArquivo.TXT tiver 1.000 linhas, dessa forma acima, serão 10 linhas x 1 arquivo = 10 execuções, e no original está sendo 10 linhas x 1000 linhas = 10.000 execuções, é muito demorado.

7. Uso de aspas, lembre-se do que comentou o @Ricardo Bohner...

Nessa parte: echo."!str!" | findstr /c:%%a>nul && ( tenta colocar uma aspas em %%a -> "%%a"

Obs.: O Finstr vai interpretar o conteúdo da string passada como o um ReGex (. *, $, ^, , 9-0, <, />, [, ], etc..., pois ele tende e trata tudo como ReGex (salvo se você usar uma das flags explicitas para que não faça isso, ou o /L ou o /C:), e o também o seu For /F vai imediatamente fechar o laço/loop em andamento se a string contém algum ):

64street;64th. Street - A Detective Story (World);Arcade;;1991;C.P. Brain;Briga de rua-Luta / 2.5D-Luta;1-2;;;;;;;;0.5;;;;;Duken

8. Substitua o Findstrt por um find "simples*, fica mais fácil usa o find para uma busca literal, onde nenhuma regex está em uso.

find "string/linhaDo.Tag" redireciona o arquivo.TXT // para o find ler na busca pela string...  
  
find "%%~i;" <"%%~nG.txt" 

9. Use aspas no seu loop for /F adicionando usebackq, ou abreviado (não documentado) useback:

Obs.: Por paranóia minha, uso também em alguns códigos onde carateres especiais podem surgir no processamento, e ainda assim, vou usar o set /p "'=String Com Caracteres Especias [espacos] , &, (, ), etc.. " <nul , mas como isso faz com que a saída do próximo comando ocorrer na mesma linha, sou obrigado a adicionar um echo\ quando é necessário escrever em tela/arquivo já quebrando a linha atual. Veja isso no primeiro código postado, (código numa versão compacta):

rem :: uso do usebackq no loop For /F aplica-se em echo, set, etc...
rem :: e o uso do set /p "'=String Escapada" <nul escapando as strings 
rem :: com aspas duplas "usecakq" + set /p "=String" mas sem ecoar/printar 
rem :: a duplicidade da aspas duplas: ""...""  em: ""String escapada""


for /f useback^delims^= %%i in (`
more "%%~G"`)do set/p "'=- ROM Found in File %%~nxG: %%~i"<nul & echo= & ( 
     <con: find "%%~i;" <"%%~nG.txt" >>".\Favorites.txt" && set/a "_num+=1")

10. Mesmo código, porém portado para uma versão/layout mais covencional:

@echo off 

set /a "_tag=0"
set /a "_num=0"

cd /d "D:\AM-2.6.1\ROMlists" 
setlocal EnableDelayedExpansion

echo==========================================================
echo=    AM Favorites ROMlist Generator Script for Windows     
echo==========================================================

if not exist .\favorites.txt (
     
      set /p "'= - Cretating .\Favorites.txt File.."<nul
      echo\
     
    )  else (
    
      set /p "'= - Backing up your old Favorites.txt: "<nul
      move /y .\Favorites.txt .\Favorites.txt.backup 2>nul >nul
      if %errorlevel% equ 0 echo\Done^!!
    )
      
echo/- Gathering list of your Favorites: Tags-Files

for %%G in (*.tag)do (
     
     set /a "_tag=!_tag! + 1"
     
     for /f "usebackq delims=" %%i in (`more "%%~G"`)do (
     
         set/p "'=- ROM Found in File %%~nxG: %%~i"<nul 
         echo= 
         
         find "%%~i;" <"%%~nG.txt" >>".\Favorites.txt"
         if %errorlevel% equ 0 set /a "_num=!_num! + 1"
         
        )
    )

set /a "_num=!_num! + 1000"
set /a "_tag=!_tag! + 1000"

call echo/- Romlist Files [tag=txt]: !_tag:~-3!
echo/- Favorites added to Disc: !_num:~-3!
echo/- ROMlist .\Favorites.txt: New

endlocal
echo/- is Done!.. 

findstr /ec:\.\Favorites\.txt "%~f0"
goto :EOF

========================================================================================
- Add a display in Attract Mode and set its ROMlist to the newly created .\Favorites.txt
========================================================================================
  This script basically does the same thing as DM's Favorites ROMlist generator but 
  on Windows [ Shouts to him for the pi version d;) ].
                                                         
  How it works:
  It grabs all the (tagged) favorites from every tag file, searches for them through
  all the ROMlists, then generates a ROMlist called Favorites.txt Written by Steve 
  Sherrod, 05/20/17, as part of project HyperPie Expanded
========================================================================================

Algums leituras adicionais

4
  • Simplesmente espetacular a sua explicação e seu codigo, ele faz em segundos o que demorava minutos obrigado por me ajudar. +1 like. 21/01/2021 às 11:14
  • @arthurvalenca Obrigado por ler/comentar/testar. Reserve um tempo para leitura do conteúdo lincado.
    – Io-ol
    21/01/2021 às 11:31
  • 1
    pode deixar Muito obrigado!!!!! 21/01/2021 às 11:40
  • @arthurvalenca se remover timeout 3| do primeiro código postado, ainda ganhas - 3 segundos na execução. Do segundo código eu removi...
    – Io-ol
    21/01/2021 às 15:14

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .