The other day I got a zip archive of a hundred xml files. The task was to identify a single key word/phrase (STR_RESTORING_FILE_FAILED) in each xml file that indicated a failure to restore a file (part of a larger job) and create a new file with just line in each xml file that matched the key word/phrase. Here’s what I did to obtain the new file:
[requirements]
Windows PC capable of running DOS
[procedure]
[step 1] Create a new batch script named find-string-copy-results-new-file.bat. Ensure that the files you want to search and pull data from are in a folder on your computer (i.e. Desktop\logs).
[step 2] Edit the following code by specifying the source and destination folders you want to use (NOTE: Destination must exist) and paste it into your editor:
@echo off
setlocal enableextensions
set "source=C:\Users\david\Desktop\logs"
set "target=C:\Users\david\Desktop\output\output.txt"
pushd "%source%"
(for /f "tokens=1,* delims=:" %%a in ('findstr /i /l /c:"STR_RESTORING_FILE_FAILED" "*.xml"') do (
echo(%%b
)) > "%target%"
popd
[step 3] Run your batch file and you’re done.
That’s it.
Comments
3 responses to “Find a string and copy its whole line to new file”
Hi,
Thanks for the script.
I wanted to copy 5 lines after finding the match. how can i do that.
Suppose match was found on line number 10, then i want to copy everything from line 5 till 10.
thanks
@echo off
setlocal EnableDelayedExpansion
rem Assemble the list of line numbers
set numbers=
for /F “delims=:” %%a in (‘findstr /I /N /C:”my search string” mylog.log’) do (
set /A first=%%a, second=%%a+1, third=%%a+2, fourth=%%a+3, fifth=%%a+4
set “numbers=!numbers!!first!: !second!: !third!: !fourth!: !fifth!: ”
)
rem Search for the lines
(for /F “tokens=1* delims=:” %%a in (‘findstr /N “^” mylog.log ^| findstr /B “%numbers%”‘) do echo %%b) > output.txt
Great script. How can I search for (2) literal strings and include them in a file ? I want to find the word “Critical” and “All Shares Ok” and have these listed in a file.