windowscmdstdoutstdin

(windows) how to pipe a command and use stdout as arguments for the next command instead of stdin


There are two main commands im using, ripgrep and gawk(awk version for windows). Im on the cmd, so i cant really use $( )

Basically i use ripgrep to find a patter in a list of markdown files:

rg --hidden --vimgrep "pattern"

The output is always something like this

path/to/file:4:1:pattern

The next step is to use awk to separate the fields with : and get only the first field, the file path:

rg --hidden --vimgrep "pattern" | awk -F":" "{print $1}"

The output will be a list of filepaths, now the thing gets a little tricky. I pipe the output to another ripgrep call:

rg --hidden --vimgrep "pattern" | awk -F":" "{print $1}" | rg --vimgrep --hidden "pattern"

Except this time i want those files to be read as part of the commands arguments, but ripgrep instead searches through the stdout instead of using that stdout as arguments to search those specific file paths.

I know in unix enviroments you could use something like xargs, however this tool isnt available in windows

My biggest problem is that actually i need to run this on the cmd, i could solve this by changing the shell, but for this specific situation i need it to be ran in the cmd

could somebody help me, please?


Solution

  • The general CMD method to run a command with argument(s) taken from a(nother) command is

    FOR /F %var IN ('command1') DO command2 %var
    

    See FOR /? or https://ss64.com/nt/for_cmd.html for help. Note var can be any single letter, and %var is doubled to %%var IN A BATCH FILE, which is what ss64 shows; it is not doubled if you enter the command directly. This can also do limited parsing that is sufficient for your need:

    for /f "tokens=1 delims=:" %v in ('rg --hidden --vimgrep "pattern"') do rg --hidden --vimgrep "pattern" %v
    

    However (g)awk is not provided by Windows; you got that as a port from someplace, like mingw (or git4win) or gnuwin32, and whereever that was/is likely has xargs also. (In particular the several-years-old git4win I have does.)

    Or awk can run things by itself, although the expressions you can pass to it from CMD have some limitations:

    awk -F: -vcmd="rg --hidden --vimgrep \"pattern\" " "{system(cmd $1)}"
    # note cmd ends with space so when concatenated to a filename it parses properly
    # I think that will get the doublequotes passed through; if not try adding ^