0

I am trying to understand the implementation of the paste command in unix when there is a file from input redirection.

Assuming the following files:

A.txt:
A
B
C
D

B.txt: 1 2 3 4

The unix command:

paste - A.txt - < B.txt

The expected output:

1    A    2
3    B    4
     C
     D

Does this mean that whenever you redirect a file into standard input, the - shares the same file for both the - (and what is this called?)

I am trying to understand why the output is different from doing something like: paste B.txt A.txt B.txt as I thought the redirected input simply replaces the - but the result is different.

Iva l
  • 1

1 Answers1

1

The documentation (man paste) writes,

With no FILE, or when FILE is -, read standard input.

When you include - as a source file, standard input (stdin) is read. Standard input has been opened by the shell and assigned to file descriptor 0, and it's from this descriptor that paste reads data. The paste command itself doesn't open anything for stdin (it can't, because there's only -) so all reads from this file descriptor are shared.

In your example, the first line of B.txt is 1 and that's used in the first field. The second line of B.txt is 2 so that's used for the second field. This continues until stdin returns EOF (End of File).

Chris Davies
  • 116,213
  • 16
  • 160
  • 287