0

In Linux/Unix command line, when using a command with multiple inputs, how can I redirect one of them?

For example, say I'm using cat to concatenate multiple files, but I only want the last few lines of one file, so my inputs are testinput1, testinput2, and tail -n 4 testinput3.

How can I do this in one line without any temporary files?

I tried tail -n 4 testinput3 | cat testinput1 testinput2, but this seems to just take in input 1 and 2.

Sorry for the bad title, I wasn't sure how to phrase it exactly.

7
  • you can use process substutution Commented Feb 7, 2018 at 3:06
  • @ymonad I tried cat testinput1 testinput2 <tail -n 4 testinput3, but as expected, that told me -bash: tail: No such file or directory. Commented Feb 7, 2018 at 3:12
  • 1
    You forgot the parents <(process) Commented Feb 7, 2018 at 3:13
  • @DavidC.Rankin I tried cat testinput1 testinput2 < <(tail -n 4 testinput3), but that only gave me the output of the first two, just like when I tried to use piping. Commented Feb 7, 2018 at 3:15
  • 2
    Sorry, see updated comment, you do not need the extra redirection cat file1 file2 <(tail -n4 file3) Commented Feb 7, 2018 at 3:18

1 Answer 1

3

Rather than trying to pipe the output of tail to cat, bash provides process substitution where the process substitution is run with its input or output connected to a FIFO or a file in /dev/fd (like your terminal tty). This allows you to treat the output of a process as if it were a file.

In the normal case you will generally redirect the output of the process substitution into a loop, e.g, while read -r line; do ##stuff; done < <(process). However, in your case, cat takes the file itself as an argument rather than reading from stdin, so you omit the initial redirection, e.g.

cat file1 file2 <(tail -n4 file3) 

So be familiar with both forms, < <(process) if you need to redirect a process as input or simply <(process) if you need the result of process to be treated as a file.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.