Good Day All.

I want to search for the following string in a bunch of TEXT files in a folder:


Then I want to copy the string next to this word (USER), and copy it to a new text file.

How do I do this? The word next to the string 'USER' will be an FTP username - All the files I am searching in are FTP logs...



Your requirements are a bit vague. The string "USER" might appear in multiple contexts. The more specific you are as to the expected line format, the better the solution.

A case senstive solution using native batch commands would be a bit tricky.

Here is a native batch solution that is not case sensitive. It looks for the word "USER" (case insensitive) either at the beginning of a line or after a space, followed by a space. It then skips one or more spaces (or tabs) and then writes out the next string up until space, tab, or end of line.

@echo off
setlocal disableDelayedExpansion
pushd "pathToYourFolder"
>userNames.txt (
  for /f delims^=^ eol^= %%A in ('findstr /ri /c:" USER " /c:" USER " *.txt') do (
    set "ln=%%A"
    setlocal enableDelayedExpansion
    set "ln=!ln:*:=!"
    if /i "!ln:~0,5!" equ "USER " (set "ln=!ln:~5!") else set "ln=!ln:* USER =!"
    for /f %%B in ("!ln!") do if "%%B" neq "" echo %%B

Life is much better if you allow yourself to go beyond native batch commands. The following uses REPL.BAT - a hybrid JScript/batch utility that performs a regular expression search and replace on lines from stdin and writes the result to stdout. It is pure script that runs natively on any modern Windows machine from XP onward.

The script below assumes REPL.BAT is somewhere within your PATH. It looks for the word USER (case sensitive) followed by one or more whitespace characters (most likely spaces and/or tabs) and then writes out the next "string" up until another whitespace character. Chances are the regular expression could be modified as needed quite easily if you better define your requirements.

pushd "pathToYourFolder"
findstr USER *.log|repl ".*?:.*\bUSER\s+(\S+).*" $1 a >userNames.txt
  • this is great. Thank you. How do I remove duplicate entries since there are users repeating throughout the logs? – DextrousDave Feb 3 '14 at 13:11

Not exactly a solution in classical bat. Powershell:

$logfiles = gci $logdir -include "*.log" -recurse

foreach ($file in $logfiles) {

    select-string -pattern "USER" $file | foreach { $_.ToString().split(" ")[2] >> $outputfile}

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.