📜  Linux 中的 cmp 命令和示例

📅  最后修改于: 2022-05-13 01:57:28.601000             🧑  作者: Mango

Linux 中的 cmp 命令和示例

Linux/UNIX 中的 cmp命令用于逐字节比较两个文件,帮助您找出两个文件是否相同。

  • 当 cmp 用于两个文件之间的比较时,如果发现差异,如果没有发现差异,比较的文件相同,它将向屏幕报告第一个不匹配的位置。
  • cmp 不显示任何消息,如果比较的文件相同,则仅返回提示。
Syntax:
cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]

SKIP1 ,SKIP2 & OPTION are optional 
and FILE1 & FILE2 refer to the filenames .

cmp 命令的语法很容易理解。如果我们比较两个文件,那么显然我们需要它们的名称作为参数(即语法中的 FILE1 和 FILE2 )。除此之外,可选的 SKIP1 和 SKIP2 指定每个文件开头要跳过的字节数,默认情况下为零,而 OPTION 指的是与此命令兼容的选项,我们将在稍后讨论。

cmp 示例:如前所述,如果发现差异,cmp 命令会报告字节和行号。现在让我们在示例的帮助下找出相同的内容。假设有两个文件要比较,一个是 file1.txt ,另一个是 file2.txt :

$cmp file1.txt file2.txt
  1. 如果文件不相同:上述命令的输出将是:
    $cmp file1.txt file2.txt
    file1.txt file2.txt differ: byte 9, line 2
    
     /*indicating that the first mismatch found in
     two files at byte 20 in second line*/
  2. 如果文件相同:您将在屏幕上看到如下内容:
    $cmp file1.txt file2.txt
    $ _
    /*indicating that the files are identical*/

cmp 命令的选项

1. -b(print-bytes) :如果您希望 cmp 在与 -b选项一起使用时在输出中显示不同的字节。



//...cmp command used with -b option...//

$cmp -b file1.txt file2.txt
file1.txt file2.txt differ: 12 byte, line 2 is 154 l 151 i

/* indicating that the difference is in 12
 byte ,which is 'l' in file1.txt and 'i' in file2.txt.*/

上面输出中的值 154 和 151 分别是这些字节的值。

2. -i [bytes-to-be-skipped] :现在,这个选项与 cmp 命令一起使用时有助于从两个文件中跳过特定数量的初始字节,然后在跳过后比较文件。这可以通过将字节数指定为 -i 命令行选项的参数来完成。

//...cmp command used with -i option...//

$cmp -i 10 file1.txt file2.txt
$_

/*indicating that both files are identical 
after 10 bytes skipped from both the files*/

请注意,在这种情况下(使用 -i 跳过字节),比较开始的字节被视为字节号零。

3. -i [要从第一个文件跳过的字节数] : [要从第二个文件跳过的字节数] :此选项与上面的 -i [要跳过的字节数] 选项非常相似,但不同的是现在它允许我们分别输入要从两个文件中跳过的字节数。

//...cmp command used with -i option...//

$cmp -i 10:12 file1.txt file2.txt
$_

/*indicating that both files are identical 
after 10 bytes skipped from first file and 
12 bytes skipped from second file*/

4. -l 选项:此选项使 cmp 命令打印所有不同字节的字节位置和字节值。

//...cmp command used with -l option...//

$cmp -l file1.txt file2.txt 
20   12   56
21  124   12
22  150  124
23  151  150
24  163  151
25   40  163
26  146   40
27  150  151
28   12   24
29  124  145
30  157  163

/*indicating that files are different 
displaying the position of differing 
bytes along with the differing bytes
 in both file*/

输出中的第一列表示不同字节的位置(字节数)。第二列代表第一个文件中不同字节的字节值,而第三列代表第二个文件中不同字节的字节值。

5. -s 选项:这允许您抑制通常由 cmp 命令产生的输出,它比较两个文件而不写入任何消息。如果文件相同,则退出值为 0,如果不同,则值为 1,如果出现错误消息,则值为 2。

//...cmp command used with -s option...//

$cmp -s file1.txt file.txt 
1

/*indicating files are different without
displaying the differing byte and line*/

6. -n [要比较的字节数] 选项:此选项允许您限制要比较的字节数,例如最多只需要比较 25 或 50 个字节。

//...cmp command used with -n option...//

$cmp -n 50 file1.txt file2.txt
$_

/*indicating files are identical for starting
50 bytes*/

8. – -v 选项:给出输出信息并退出。

9. – -help 选项:显示帮助信息并退出。