TheDude
TheDude

Reputation: 99

Separate first and last names with for loop


I'm working on a batch that creates a .txt-file from a record. The file will be processed later by another program.

The record looks like this at the moment:

11111;Lastname Firstname SecondFirstname;1234567;SomeText
22222;Lastname Firstname;1254557;SomeText
33333;Lastname Firstname;1234567;SomeText

I would like to have a semicolon between the last name and the first name. The problem is the sentences with two first names. Here should be no semicolon between the names.

In the end it should look like this:

11111;Lastname;Firstname SecondFirstname;1234567;SomeText
22222;Lastname;Firstname;1254557;SomeText
33333;Lastname;Firstname;1234567;SomeText

Does anyone have an idea here?
I have tried the following but that does not solve the problem with the two first names:

type nul>tmp.txt
for /f "delims=: tokens=1*" %%i in ('findstr /n "^" "test_output.txt"') do set "Zeile=%%j" &call :sub
move /y "tmp.txt" "test_output.txt"

goto :eof


:sub
if not defined Zeile (
    >>tmp.txt echo.
    goto :eof
)
>>tmp.txt echo %Zeile: =;%
goto :eof

Upvotes: 0

Views: 147

Answers (2)

user6811411
user6811411

Reputation:

You need two nested for /F the first to split at the semicolon, the 2nd to split at the space limited to 2 splits.

Using uppercase %A and lowercase %a for the meta variables, in cmd line:

for /F "tokens=1-3* delims=;" %A in (test_output.txt) do @for /F "tokens=1*" %a in ("%B") do @Echo %A;%a;%b;%C;%D

In a batch file saving to new_output.txt:

:: Q:\Test\2019\06\04\SO_56443069.cmd
@Echo off&SetLocal EnableDelayedExpansion

(for /F "tokens=1-3* delims=;" %%A in (test_output.txt
  ) do for /F "tokens=1*" %%a in ("%%B"
  ) do Echo %%A;%%a;%%b;%%C;%%D
) >new_output.txt 

Sample output:

> type new_output.txt
11111;Lastname;Firstname SecondFirstname;1234567;SomeText
22222;Lastname;Firstname;1254557;SomeText
33333;Lastname;Firstname;1234567;SomeText

Upvotes: 2

Stephan
Stephan

Reputation: 56190

Parsing the first time by the ; delimiter and parsing the second token (the third, if you take the line numbers into account) a second time by a <SPACE> delimiter (with tokens=1,*) solves your problem:

@echo off
(for /f "tokens=1-3,* delims=;:" %%A in ('findstr /n "^" "test_output.txt"') do (
if "%%B"=="" echo/
  for /f "tokens=1,*" %%M in ("%%C") do (
   echo/%%B;%%M;%%N;%%D
  )
))>tmp.txt
goto :eof

(redirecting the whole output at once is a lot faster than redirecting single lines - especially with big files)

Upvotes: 2

Related Questions