Search code examples
batch-filecmdfindstr

Shell output redirect to multiple pipes


In cmd.exe, a certain command produces output in the form:

Asd foo content 1
Qwe bar content 1
Asd foo content 2
Qwe bar content 2
...

I would like to format it to instead produce:

foo content 1, bar content 1
foo content 2, bar content 2

How do I do that?

My guess is that a combination of "&" (parallel command), "|" (pipe), "findstr" and another command to cut out the relevant parts of a line can be used.


Solution

  • You should be able to pipe the results of your command into sed for Windows, but that would require a download of a non-native utility. The GnuWin project has a free version of sed.

    Here is a native batch solution that doesn't require any download.

    @echo off
    setlocal disableDelayedExpansion
    for /f "delims=" %%A in ('yourCommand') do (
      set "ln=%%A"
      setlocal enableDelayedExpansion
      set "ln2=!ln:*foo =foo !"
      if "!ln2!" neq "!ln!" (
        <nul set /p "=!ln2!"
      ) else (
        echo , !ln:*bar =bar !
      )
      endlocal
    )
    

    The above will discard lines that begin with a ;, and will also discard empty lines. Both limitations can be solved with extra code if needed.

    The toggling of delayed expansion within the loop is done to preserve any ! character that might appear in the output. The result will be corrupted if the output contains ! and delayed expansion is enabled when the FOR variable is expanded.