Concatenate contents from stdout and from file

How can we concatenate results from stdout (or stderr) and a file into a final file.

For example

ls -a | grep text1

concatenate with file2.txt into a final result (not file2.txt), without storing grep text1 to something intermediate such as grep text1 > file1.txt

Asked By: Kenny


You can just append it on to the end of file2.txt by doing

ls -a | grep text1 >> file2.txt

Or if you want it in a different file

ls -a | grep text1 > output.txt
cat file2.txt >> output.txt

If you want the stderr instead of stdout

ls -a | grep text1 2>> output.txt

Note that this probably won’t put anything in your file since ls -a is unlikely to output anything to stderr.

EDIT: If you want to pipe the results to another program instead of redirecting to a file you’ll probably want to use named pipes.

mkfifo pipe1
cat pipe1 | next program &
ls -a | grep text1 >> pipe1
cat file2.txt >> pipe1
Answered By: David King

You can do something like below

ls -a | grep text1 >> file2.txt 2>&1

2>&1 will redirect standard err to std output

Answered By: Ajay
ls -a | grep text1 | cat file2.txt -

The - stands for standard input. Alternatively you may write

ls -a | grep text1 | cat - file2.txt

to have the output in different order.

Yet another possibility using process substitution:

cat <(ls -a | grep text1) file2.txt

or in different order:

cat file2.txt <(ls -a | grep text1)
Answered By: jimmij

You can group commands together with {} or () and redirect their combined outputs:

  cat file1.txt
  echo "Now the ls/grep"
  ls -a |grep foobar
} > file2.txt

As a oneliner:

{ cat file1.txt; echo "Now the ls/grep"; ls -a |grep foobar; } >file2.txt 

That last ; is necessary.

Answered By: Otheus
ls -a | { grep text1; cat file2.txt; } >outfile

Here ls writes to grep which writes to a stdout it shares with the cat process that launches when its through filtering ls‘s output. When grep‘s cat writes a copy of file2.txt to the same shared stdout. Fewer pipes this way, usually.

… or …

ls -a | sed -ne'$r file2.txt' -e'/text1/p' >outfile

Here sed stands in for grep and filters the input to output by printing only matches for a text1 regexp. When it reaches the $ last of ls‘s output, it schedules a read of file2.txt to output to occur after it has completely finished the current line cycle – and so as soon as it prints (or doesn’t print) the last line of ls‘s output, it copies all of file2.txt to its stdout as well.

Answered By: mikeserv
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.