0

I have seen several examples of what I need, and have tried modifying those without success.

Starting information:

a:b:c:d:e:f

Desired Format:

a:b

Information will be pasted in 1 text file paste_here.txt and output should go to a new file check.txt.

My current attempt is:

@echo off
setlocal

for /f "tokens=1,2 delims=:" %%a in (paste_here.txt) do (echo %%a >> check.txt)
1

Your question is not clear. Providing sample input and output is a good thing, but you should also explain your requirements.

I assume you have multiple colon delimited columns on each line, and you want to preserve the first two columns of every line. I'm also assuming that the column widths are variable, even though your example has only once character per column.

Your code is only preserving the first column. It is not hard to preserve the second:

@echo off
setlocal
for /f "tokens=1,2 delims=:" %%A in (paste_here.txt) do >>check.txt echo %%A:%%B

But there is a potential problem - it will fail if the 2nd column is missing. For example,

a::c:d:e:f

will yield

a:c

because consecutive delimiters are treated by FOR /F as a single delimiter.

It is not hard to fix, but it requires some advanced batch techniques.

  • You can preserve the entire line in an outer loop and use search/replace to enclose each column in quotes. Then a 2nd loop can be used to parse the columns and the ~ modifier to remove the quotes during output.

  • Delayed expansion is required to work with variables that are set and expanded within the same loop.

  • Delayed expansion is toggled on and off to protect ! that may appear in the content. FOR variable content with ! will be corrupted if it is expanded while delayed expansion is enabled.

  • The odd option syntax in the outer FOR /F statement is a way to disable the EOL option and to set DELIMS to nothing so that it preserves the entire line, regardless of content.

Also note that it is more efficient (faster) to use parentheses and redirect once for the entire file instead of once per line.

@echo off
setlocal disableDelayedExpansion
>check.txt (
  for /f delims^=^ eol^= %%A in (paste_here.txt) do (
    set "ln=%%A"
    setlocal enableDelayedExpansion
    set "ln="!ln::=":"!""
    for /f "tokens=1,2 delims=:" %%B in ("!ln!") do echo %%~B:%%~C
    endlocal
  )
)

Or you could use a hybrid JScript/batch utility called REPL.BAT to very efficiently accomplish your task in one step. REPL.BAT performs a regex search/replace on stdin and writes the result to stdout. It is pure script that will run on any Windows machine from XP onward.

type paste_here.txt | repl "^(.*?:.*?):.*" $1 >check.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.