Batch File - Search for string and copy next word to new file

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

DextrousDave

Posted 2014-01-23T11:43:01.473

Reputation: 385

Answers

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

dbenham

Posted 2014-01-23T11:43:01.473

Reputation: 9 212

this is great. Thank you. How do I remove duplicate entries since there are users repeating throughout the logs? – DextrousDave – 2014-02-03T13:11:46.867

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

chingNotCHing

Posted 2014-01-23T11:43:01.473

Reputation: 876