[Tex/LaTex] Write Latex code for appendix within chapter but typeset at end of book

appendices

Is it possible to enter the source code for an appendix section within the actual chapter but get it typeset after the last chapter of book?

For example something that looks like this in the code:

\chapter{Chapter 1}
\section{Section 1}
This is the first section of the first chapter. For details see Appendix 1.
\begin{appendices}
\section{Appendix for Chapter 1, Section 1}
Here is additional information that is typeset at the end of the book.
\end{appendices}
\chapter{Chapter 2}
\section{A new section}
This is a new section in the second Chapter. Even though I add a new appendix here, it will become consolidated with the first appendix at the end of the book.
\begin{appendices}
\section{Appendix for a new section}
This is the appendix for "A new section" in Chapter 2
\end{appendices}

and produces this as the output:

Chapter 1

1.1 Section 1

This is the first section of the first chapter. For details see
Appendix 1.

Chapter 2

2.1 A new section

This is a new section in the second Chapter. Even though I add a new
appendix here, it will become consolidated with the first appendix at
the end of the book.

Appendices

A. Appendix for Chapter 1, Section 1

Here is additional information that is typeset at the end of the book.

B. Appendix for a new section

This is the appendix for "A new section" in Chapter 2

Best Answer

This is a modification of https://tex.stackexchange.com/a/186907/4427

\documentclass{book}
\usepackage{environ}

\newtoks\mainnotetoks
\newtoks\tempnotetoks
\newtoks\prenotetoks
\newtoks\postnotetoks

\NewEnviron{appendixatend}{%
  \tempnotetoks=\expandafter{\BODY}%
  \edef\notetemp{%
    \the\mainnotetoks % what was already stored
    \the\prenotetoks % text before the new note
    \the\tempnotetoks % the current note
    \the\postnotetoks % text after the new note
  }%
  % update \mainnotetoks
  \global\mainnotetoks=\expandafter{\notetemp}%
}
\newcommand\includeappendices{%
  \appendix
  \chapter*{Appendix}
  \renewcommand{\thesection}{\Alph{section}}
  \the\mainnotetoks}

% set the pre and post note
\prenotetoks={}
\postnotetoks={}

\begin{document}
\mainmatter

\chapter{Chapter 1}
\section{Section 1}
This is the first section of the first chapter. For details see Appendix 1.
\begin{appendixatend}
\section{Appendix for Chapter 1, Section 1}
Here is additional information that is typeset at the end of the book.
\end{appendixatend}
\chapter{Chapter 2}
\section{A new section}
This is a new section in the second Chapter. Even though I add a new appendix here, it will become consolidated with the first appendix at the end of the book.
\begin{appendixatend}
\section{Appendix for a new section}
This is the appendix for "A new section" in Chapter 2
\end{appendixatend}

\includeappendices
\end{document}

enter image description here