It is too easy to make error report in the bedGraphToBigWig process. I want to save the time for the fresh people. The following procedure would be work well for majority situations.
1, bedGraph should be without header before sorting
awk 'NR!=1' input.bedGraph > input.deheader.bedGraph
2, bedGraph should be sorted
sort -k1,1 -k2,2n unsorted.bedGraph > sorted.bedGraph
3, chorsome length should be same with Bam files
fetchChromSizes hg19 > hg19.chrom.sizes
4, Be sure the bedGraph should only have 4 column
awk '{print $1,$2,$3,$4}' NC-P-2.bedGraph_CpG.sort.bedGraph > NC-P-2.bedGraph_CpG.sort.4.bedGraph
5, Now, you can run the script (bedGraphToBigWig input.sort.bam chrome.size output.bw)
Summary, You can use the following two step to do bedGraphtobigwig transformation:
(head -n 1 NC-P-25.bedGraph_CpG.bedGraph && tail -n +2 NC-P-25.bedGraph_CpG.bedGraph | sort -k1,1 -k2,2n | awk '{print $1,$2,$3,$4}' OFS="t" ) > NC-P-25.bedGraph_CpG.bedGraph.sort bedGraphToBigWig NC-P-25.bedGraph_CpG.bedGraph.sort hg19.chrom.sizes NC-P-2.bw
For large number of bedGraph files:
# bedgraph to bigwig
for i in `ls *bedGraph`
do
(head -n 1 $i && tail -n +2 $i | sort -k1,1 -k2,2n | awk '{print $1,$2,$3,$4}' OFS="t" ) > $i.sort
bedGraphToBigWig $i.sort ~/oasis/db/hg19/hg19.chrom.sizes $i.bw
done
..