diff --git a/bin/hicstuff_build_matrix.py b/bin/hicstuff_build_matrix.py
index 8c47ac311b89a0ab3a11f765757f5d953a0d0ec6..4ac69c15e4d42a22b3f69a5ab8b03dd5d6224d24 100755
--- a/bin/hicstuff_build_matrix.py
+++ b/bin/hicstuff_build_matrix.py
@@ -71,9 +71,6 @@ def pairs2matrix(
     #     tmp_dir=tmp_dir,
     # )
 
-    cmd = 'grep -v ^# %s | sort -S 2G -k8,8n -k9,9n --parallel=1' % pairs_file
-    with open(pre_mat_file, "w") as fout:
-        fout.write(str(os.system(cmd)))
 
     header_size = len(hio.get_pairs_header(pre_mat_file))
     with open(pre_mat_file, "r") as pairs, open(mat_file, "w") as mat:
diff --git a/modules/local/hicstuff/build_matrix.nf b/modules/local/hicstuff/build_matrix.nf
index 4d531e94bc82cebc697fbae63730aac58608fc79..f2db7783dffa008b84c5cf8f607bc9e1cdf3efa7 100644
--- a/modules/local/hicstuff/build_matrix.nf
+++ b/modules/local/hicstuff/build_matrix.nf
@@ -17,7 +17,9 @@ process BUILD_MATRIX {
     def args = task.ext.args ?: ''
 
     """
-    hicstuff_build_matrix.py -p ${idx_pairs} -f ${fragments_list} -t graal -o ${args}
+    grep -e ^# ${idx_pairs} > ${args}.pre.pairs
+    grep -v ^# ${idx_pairs} | sort -S 2G -k8,8n -k9,9n --parallel=1 >> ${args}.pre.pairs
+    hicstuff_build_matrix.py -p ${args}.pre.pairs -f ${fragments_list} -t graal -o ${args}
 
     mv ${args} ${meta1.id}_${args}
     """