Experimente o seguinte código,
rev Header.txt Detail.txt | awk ' /DH/{$4=1}1' FS="" OFS="" | sort | awk ' /DH/{$4="A"}1' FS="" OFS="" | rev | column -t > Merge.txt
Saída:
20180731 HD0000000000000000000000007AAAA
20180731 1AAAA
20180731 2AAAA
20180731 3AAAA
20180731 4AAAA
20180731 5AAAA
20180731 6AAAA
20180731 7AAAA
20180731 HD0000000000000000000000003AAAB
20180731 1AAAB
20180731 2AAAB
20180731 3AAAB
20180731 HD0000000000000000000000002AAAC
20180731 1AAAC
20180731 2AAAC
20180731 HD0000000000000000000000004AAAD
20180731 1AAAD
20180731 2AAAD
20180731 3AAAD
20180731 4AAAD