James Thomas
James Thomas

Reputation: 3

How to break a string based on a word in a txt file with batch script

I have been reading around here for several days, and I have found many shared scripts but it doesn't appear that those shared here can help me with my request, I have also looked online and I can't seem to find how to do this

If you have a question here that was already ask, that will do exactly what I have ask, please provide a link and feel free to close my question, and I am sorry if I asked a repeated question

my file is under word wrap, and I would like to find the word code and return it, like if I placed the cursor in front of the word code and I press enter

Version model 173838r8, "code": data of strings, "code": data of strings, "code": data of strings,

.

Version model 173838r8,
"code": data of strings,
"code": data of strings,
"code": data of strings,

Upvotes: 0

Views: 56

Answers (2)

Aacini
Aacini

Reputation: 67196

Your question is pretty confusing to me... This phrase: "my file is under word wrap, and I would like to find the word code and return it, like if I placed the cursor in front of the word code and I press enter" have no sense...

The question is "How to break a string based on a word" but you didn't specified which word is used to break the string!

I assumed that you want to "break a string at , (comma-space) delimiters":

@echo off
setlocal EnableDelayedExpansion

for /F "delims=" %%a in (test.txt) do (
   set "line=%%a"
   for %%n in (^"^
%Don't remove this line%
^") do echo !line:, =,%%~n!
)

This code just replaces comma-space by comma-newline characters...

EDIT: Test output added

This is my input file:

Version model 173838r8, "code": data of strings, "code": data of strings, "code": data of strings,

and this is the output:

Version model 173838r8,
"code": data of strings,
"code": data of strings,
"code": data of strings,

Upvotes: 0

Magoo
Magoo

Reputation: 79982

@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q75792000.txt"

REM (
FOR /f "usebackqdelims=" %%e IN ("%filename1%") DO (
 SET "line=%%e"
 CALL :process
)

GOTO :EOF

:process
SET "line=%line:, =,|%"
:processloop
FOR /f "tokens=1*delims=|" %%b IN ("%line%") DO ECHO %%b&SET "line=%%c"&IF DEFINED line GOTO processloop
GOTO :eof

Always verify against a test directory before applying to real data.

Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around %filename1% can be omitted.

I've made a number of assumptions for lack of clarity, mainly that | is never encountered in the source data.

Upvotes: 0

Related Questions