Linux中的cmp命令及其示例

化学机械抛光 Linux/UNIX中的命令用于逐字节比较这两个文件,并帮助您确定这两个文件是否相同。

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

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

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

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(打印字节): 如果需要,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[要跳过的字节]: 现在,当与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跳过字节),比较开始的字节被视为字节号0。

3.-i[从第一个文件跳过的字节]:[从第二个文件跳过的字节]: 这个选项与上面的-i[bytes to skipped]选项非常相似,但区别在于现在它 允许我们输入要跳过的字节数 分别从两个文件中删除。

//...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.––帮助选项: 这将显示一条帮助消息并退出。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享