0

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

2 Answers 2

1

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
    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
1
  • this is great. Thank you. How do I remove duplicate entries since there are users repeating throughout the logs? Feb 3, 2014 at 13:11
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .