wchmb
wchmb

Reputation: 1354

Redirect a pipe chain

Let's suppose the output of a chain of pipes command1 | command2 is the name of a file and you want to redirect < this file to another command.

I'd like to use something like command3 < command1 | command2 but it seems that < operator has preference over |

How to do that without the using of subshells nor subtitutions, just using pipes and redirections?

Example (*):

I'd like to search for the "hello" word in the most recent file doing something like:

grep "hello" < ls -t | head -n1

These solutions from SO users are not valid for me:

grep "hello" $(ls -t | head -n1)      # command subtitution
ls -t | head -n1 | xargs grep "hello" # no redirection

--

(*) This is just an example, I know I don't need redirection for grep. I'm not asking for a particular solution of this example.

Upvotes: 0

Views: 792

Answers (2)

Aaron
Aaron

Reputation: 24812

You can use xargs cat :

command1 | command2 | command3 | xargs cat | command4

xargs will execute the command passed as argument for each line of its standard input. Its standard input here is fed by your pipeline producing a filename, so xargs cat will output the content of that file, which is then piped to command4.

You can try it here.

Upvotes: 1

Saboteur
Saboteur

Reputation: 1428

command4 < command1 | command2 | comamnd3

Why don't move your command to the end of pipechain, as it should be logical? :

command1 | command2 | command3 | command4

| is not just a redirection, it is pipe with redirection between two separate processes, when < and > are redirection of stdout/stdin belong to the same process, that is why they executes before '|' pipe.

If you want to put your command4 in the beginning by any personal reasons, you can use ( ) to join other commands and then redirect the result using "<<<" redirection, like that:

command4 <<< ( command1 | command2 | command3 )

And your example:

grep "hello" < ls -t | head -n1 (*)

For such things you can use xargs:

ls -t | head -n1 | xargs grep "hello"

Upvotes: 1

Related Questions