Home > front end >  For loop function for single line in batch?
For loop function for single line in batch?

Time:11-21

I have a txt file which contains some animal and fruit names. * contain fruits and # contain animal. Just like below:-

*   apple
#  cat
*   banana
#   dog
*   mango
#   lion
*   graps

I want to sort down list and write like a table which given below:-

*  apple                   #  cat
*  banana               #  dog
*  mango               #  lion

I'm using a for loop for this:

for /f "useback eol=* tokens=1-5 delims= " %%a in ("my text.txt") do (
for /f "useback eol=# tokens=1-5 delims= " %%c in ("my text.txt") do (
Echo %%a   %%b
))

But it echoes duplicates.

CodePudding user response:

This can be done in cmd or a batch-file using the following. If you are on a supported Windows system, PowerShell is available.

This code get the entire file contents into memory, the splits it into an array on the * character. The first, empty, array element is skipped. Then, the NewLine between the * and # lines is replaced with a few SPACE characters.

powershell.exe -NoLogo -NoProfile -Command ^
    "(Get-Content -Path '.\fruit-animal.txt' -Raw) -split '\*' | Select-Object -Skip 1 | %{ '*   '   $_ -replace [Environment]::NewLine, '    '}"

Here is the data file and example execution.

C:>TYPE .\fruit-animal.txt
*   apple
#  cat
*   banana
#   dog
*   mango
#   lion
*   graps

C:>powershell.exe -NoLogo -NoProfile -Command ^
More?     "(Get-Content -Path '.\fruit-animal.txt' -Raw) -split '\*' | Select-Object -Skip 1 | %{ $_ -replace [Environment]::NewLine, '    '}"
   apple    #  cat
   banana    #   dog
   mango    #   lion
   graps

This will likely work well for you unless you have a -large- file.

If PowerShell Core http://github.com/PowerShell/Powershell is used (recommended), change it to:

pwsh.exe -NoLogo -NoProfile -Command ^
    "(Get-Content -Path '.\fruit-animal.txt' -Raw) -split '\*' | Select-Object -Skip 1 | %{ '*   '   $_ -replace [Environment]::NewLine, '    '}"

CodePudding user response:

The task description, the example input and output data and the posted code do not match at all. So it is really difficult to understand what the task really is.

The first batch file code below is for reading all non-empty lines from a data file and merge each non-empty odd line with each non-empty even line together and finally replace the source data file with the temporary file containing the merged lines.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "DataFile=Data.txt"
if not exist "           
  • Related