Set variable with highest existing number in file

Asked

Viewed 130 times

2

I have a file named "list.txt" with the content below:

1
10
1000
333
46
4611116
498

I need to create another file, called "Lista2.txt" ordered from the largest to the smallest using a batch file. I tried a few things like using the command Sort, but there’s no right way out.

sort /r lista.txt /o lista2.txt

But the result is incorrect

498
4611116
46
333
1000
10
1

2 answers

1


The Sort is not working because it is comparing alphabetically and not numerically. One way to fix this is to add digits "0" or " "(space) at the beginning of all numbers so that they all have the same number of characters. This way the Sort ordering will work.

According to this reply, a way to do this with a batch file is as follows:

@echo off
setlocal enabledelayedexpansion

REM Adiciona 12 espaços na frente de cada linha do arquivo:
(for /f %%i in (lista.txt) do (
    REM 12 espaços:
    set "Z=            %%i"
    REM Com esse resultado, pegue os últimos 12 caracteres, e salve num arquivo temporário:
    echo !Z:~-12!
))>temp.txt 

REM usando o sort:'
sort /r temp.txt /o temp.txt

REM removendo os espaços iniciais que foram postos inicialmente:
(for /f %%i in (temp.txt) do echo/%%i)>lista2.txt
REM deletando o arquivo temporário.
del temp.txt

Of course, you need to make sure that there is no temp.txt file in the same folder as it will be lost, and that no number will have more than 12 digits. If this is the case, you can add more spaces to the algorithm. There are other, more elegant ways to solve this problem, but it remains as close as possible to the approach taken.

  • exactly that, thank you very much ;)

1

A hint using the commands set along with find in a loop for ordering from major to minor.


@echo off && setlocal enabledelayedexpansion 

cd /d "%~dp0" & (for /f %%i in (lista.txt)do set "_list=!_list!,%%i,") && set "_list=!_list:,,=,!"
for %%i in (!_list!-99999999)do for %%I in (!_list!)do if %%i lss %%I echo/!_x!|find ",%%I,">nul||set "_x=!_x!,%%I,"
cd.>lista2.txt & for %%i in (!_x!)do echo/%%i>>lista2.txt

for /f %%M in (lista2.txt) do echo=Maior Valor: %%M & goto :^)

:^)
type .\lista2.txt & timeout -1

inserir a descrição da imagem aqui


Commented code:


@echo off && setlocal enabledelayedexpansion 

:: entra na pasta do bat ::
cd /d "%~dp0" 

:: looping for criando array _list dos itens/linhas do arquivo :: 
for /f %%i in (lista.txt)do set "_list=!_list!,%%i," 

:: remove duplicidade de virgulas no array :: 
set "_list=!_list:,,=,!"

:: usa o array em 2 loopings for para verificar %%i e %%I qual é maior para salvar no  array _x :: 
for %%i in (!_list!-99999999)do for %%I in (!_list!)do if %%i lss %%I echo/!_x!|find ",%%I,">nul||set "_x=!_x!,%%I,"

:: cria arquivo lista2.txt com os itens armazenados no array _x :: 
cd.>lista2.txt & for %%i in (!_x!)do echo/%%i>>lista2.txt

:: lista o primeira linha (maior valor salvo no lista2.txt) e exibe saido para lable :^) :: 
for /f %%M in (lista2.txt) do echo=Maior Valor: %%M & goto :^)


:^)
:: lista as linhas do maior valor para o menor salvo no lista2.txt e chama um pause :: 
type .\lista2.txt & timeout -1

An option for a looping limiting the execution based on the number of lines in the list.txt file:


@echo off && setlocal enabledelayedexpansion & cd /d "%~dp0" 

for /f delims^=:^ tokens^=^2 %%i in ('find /c /v ";" lista.txt')do set _cnt=%%i
2>nul (cd.>"%temp%\_lista_.tmp" & cd.>"lista2.txt") & for /f %%i in (lista.txt)do echo/,%%i,>>"%tmp%\_lista_.tmp"
for /l %%L in (1 1 99999)do find ",%%L," "%temp%\_lista_.tmp" >nul && (echo/%%L>>"lista2.txt" & call set /a "_cnt-=1" && if "!_cnt!" =="0" goto :~0)

:~0  
timeout -1 & del "%temp%\_lista_.tmp" & type "lista2.txt"

Commenting option for a looping limiting the execution based on the number of lines in the file


:: conta as linhas/numeros estao no arquivo para usar como delimitador de execução no for /l ::
for /f delims^=:^ tokens^=^2 %%i in ('find /c /v ";" lista.txt')do set _cnt=%%i

:: cria os 2 arquivos vazios e se para caso de existirem, apaga o conteudo ::
2>nul (cd.>"%temp%\_lista_.tmp" & cd.>"lista2.txt")

:: cria string unica para cada numero/linha do arquivo "%tmp%\_lista_.tmp" ::
for /f %%i in (lista.txt)do echo/,%%i,>>"%tmp%\_lista_.tmp"

:: executa um loop numerico de 1 em 1 ate 99999, e tambem localiza ",numero," no arquivo "%tmp%\_lista_.tmp" ::
:: remove as ",," (virgulas) da string, salva (se existente), somente o numero da varivel %%L em "lista2.txt" ::
for /l %%L in (1 1 99999)do find ",%%L," "%temp%\_lista_.tmp" >nul && echo/%%L>>"lista2.txt"

:: para cada ocorencia, vai substraindo 1 do contador _cnt, para quando chegar em zero parar de listar/buscar ::
&& (echo/%%L>>"lista2.txt" & call set /a "_cnt-=1" && if "!_cnt!" =="0" goto :~0)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.