首页 > 解决方案 > 合并和拆分,在 bash 中使用 csplit

问题描述

我正在合并三个三个文件(ls -l):

-rw-rw-r-- 1 kacper kacper 1839510 sie 13 14:27 A.jpg
-rw-rw-r-- 1 kacper kacper 2014809 sie 13 14:27 B.jpg
-rw-rw-r-- 1 kacper kacper 1277047 sie 13 14:27 C.pdf

使用以下命令在 bash 中合并到一个文件中:

cat A.jpg >> merged 
echo $SEPARATOR >> merged 
cat B.jpg >> merged 
echo $SEPARATOR >> merged 
cat C.pdf >> merged

在哪里:

SEPARATOR=PO56WLH82SN1ZS5QH5EU9FOZVLBRLHAGHO3D5KOUSPMS6KYSFAYN2DBL

接下来,我使用以下方法将合并的文件分成三部分:

csplit --suppress-matched merged --prefix="PART_" '/'$SEPARATOR'/' {*}

这将产生 PART_00、PART_01、PART_02 (ls -l):

-rw-rw-r--  1 kacper kacper 1839398 sie 13 18:41 PART_00
-rw-rw-r--  1 kacper kacper 2014507 sie 13 18:41 PART_01
-rw-rw-r--  1 kacper kacper 1277047 sie 13 18:41 PART_02

PART_00 和 PART_01 为 JPG 文件,可以正常显示。PART_02 是一个 PDF 文件,可以打开和查看。所以,乍一看,这在我看来是成功的。

问题是 PART_00(1839398 字节)的大小略小于 A.jpg(1839510 字节)。其他文件(PART_01、B.jpg 和 PART_02、C.pdf)也是如此。使用逐字节检查文件后

cmp

直到其中一个文件结束时,这对文件完全相同。

有谁知道为什么会这样?建议将不胜感激。

标签: bashmergesizecsplit

解决方案


The last lines in the files are not terminated by a newline character. As such, when you add your separator into the merged file you are adding it to the end of the last line in the files. This last line is then matched by csplit and the entire line dropped. Hence the last few characters are being dropped.

The --supress-matched option for csplit will supress the entire line matching where the pattern is matched.


推荐阅读