Benobab February 2016

Find String in text file using batch script

I would like to loop on every line of my .txt file within my batch script, and get every string in it.

My file is like

'string number 1' 'string number 2' 'string number 3'
'string number 11' 'string just string'
//...

And I would like to know how to get every strings surrounded by simple quotes.

I hope I'm clear enough.

Thanks for your help !

Answers


Magoo February 2016

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "outfile=%destdir%\outfile.txt"
SET "filename1=%sourcedir%\q35266036.txt"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 SET "line=%%a"
 SET "line=!line:'="!"
 FOR %%w IN (!line!) DO echo '%%~w'
)
)>"%outfile%"

GOTO :EOF

You would need to change the settings of sourcedir and destdir to suit your circumstances.

I used a file named q35266036.txt containing your data for my testing.

Produces the file defined as %outfile%

Simply, read each file to %%a then put in line for strng-manipulation.

replace each ' with "

process as a space-separated list of double-quotes strings.

remove the quotes and replace with single-quotes (if required)


Revision to save first 2 items

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "outfile=%destdir%\outfile.txt"
SET "filename1=%sourcedir%\q35266036.txt"
set "item1="
set "item2="
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 SET "line=%%a"
 SET "line=!line:'="!"
 FOR %%w IN (!line!) DO (
  echo '%%~w'
  if defined item1 if not defined item2 set "item2=%%~w"
  if not defined item1 set "item1=%%~w"
 )
)
)>"%outfile%"

echo item1=%item1%
echo item2=%item2%

GOTO :EOF

Post Status

Asked in February 2016
Viewed 2,331 times
Voted 7
Answered 1 times

Search




Leave an answer