Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Good Day All.

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

USER

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...

Thanks

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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 solutionn using native batch commands would be a bit tricky.

Here is a native batch slution that is not case sensitive. It looks for the word "USER" (case insesitive) 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
    endlocal
  )
)
popd

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
popd
share|improve this answer
    
this is great. Thank you. How do I remove duplicate entries since there are users repeating throughout the logs? –  DextrousDave Feb 3 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}
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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