If I understand your question correctly, you can do it using samtools sort with -O command:
samtools sort -O sam -T sample.sort -o sample.sort.sam sample.sam
where: -O is to specify output format; -T is to specify prefix, and I think it's needed because samtools sort create a few temporary files with this prefix; -o is your output file name. sample.sam is the original input.
Doing so, you basically sort sam file, and directly output sam file in one command.
Samtools has a build in sort command. If you're interested in knowing more about any command or program usually > x.sh --help or > x.sh -h works. For some bash command typing 'man' before a command opens the manual
2018: with a recent samtools , the syntax has changed and you don't need to use 'samtools view'
I have tried to use the below pipeline based on the above suggestion.
The subsequent step is failing with error message
sorted.bam is not coordinate sorted.To my surprise, though the step has completed successfully, it created an empty file.
Could you please help me understand what might be the reason?
This has been posted in a new thread not to hijack this unnoticed one.
samtools error when using pipeline view/sort/index