linux shell 脚本攻略学习10--生成任意大小的文件和文本文件的交集与差集详解

一、生成任意大小的文件(dd命令):

举例:

amosli@amosli-pc:~/learn/example$ dd if=/dev/zero of=test.zip bs=2M count=1;
1+0 records in
1+0 records out
2097152 bytes (2.1 MB) copied, 0.0115033 s, 182 MB/s
amosli@amosli-pc:~/learn/example$ ls
test.zip

dd命令介绍:创建特定大小的文件最简单的方法就是使用dd命令,dd命令会克隆给定的输入内容然后将一模一样的一份副本写入到输出。stdin,设备文件,普通文件都可以作为输入,stdout,设备文件,普通文件等都可以作为输出。

对于上面的例子:上面的例子创建了一个test.zip文件,大小为2M,其中if参数并不是判断语句如果的意思,它是input file的缩写,of 是output file 的缩写,bs 代表的是以字节为单位的块大小,block size,count 表示需要被复制的块数。

我们瘵bs指定为2M,count 指定为1得到了一个大小为2M的文件,如果count 为n,那么将得到n*2大小的文件。

单元大小                代  码
字节(1B)                     c
字(2B)                         w
块(512B)                         b
千字节(1024B)                     k
兆字节(1024KB)                    M
吉字节(1024M)                    G

下面是代表内存的操作速度:

2097152 bytes (2.1 MB) copied, 0.0115033 s, 182 MB/s

二、文本文件的交集与差集(comm命令)

交集(intersection)和差集(set difference)是数学上的基本概念。下面用comm命令来对文本文件进行比较。

举例:

a.txt ,b.txt

amosli@amosli-pc:~/learn/example$ cat a.txt  b.txt 
aple   #a.txt
orange
gold
iron

orange #b.txt
gold
cookies

给两者排序:

amosli@amosli-pc:~/learn/example$ sort a.txt -o a.txt ;
amosli@amosli-pc:~/learn/example$ sort b.txt -o b.txt ;
amosli@amosli-pc:~/learn/example$ cat a.txt b.txt ;

aple #a.txt
gold
iron
orange

cookies #b.txt
gold
orange

比较两者:

amosli@amosli-pc:~/learn/example$ comm a.txt  b.txt ;
        
aple
    cookies
        gold
iron
        orange
amosli@amosli-pc:~/learn/example$ 

说明:第一列表示只在a.txt 中出现过的数据,第二列表示只在b.txt中出现过的数据,第三列表示两者的交集。

可选参数:

-1 表示从输出中删除第一列

-2表示从输出中删除第二列

-3表示从输出中删除第三列

举例:

取两者交集(删除第一、二列):

amosli@amosli-pc:~/learn/example$ comm a.txt b.txt  -1 -2 ; 

gold
orange

取两者不同的值合并到一块:

amosli@amosli-pc:~/learn/example$ comm a.txt b.txt  -3 | sed 's/^	//'; 
aple
cookies
iron

上面用到了sed命令,sed中的s表示替换(substitute),/^ /表示行首的 (制表符),//表示空,用空来替换即表示删除行首的 ,然后合并输出。

那么两者的差集是什么样的?

amosli@amosli-pc:~/learn/example$ comm a.txt b.txt -1 -3
cookies

a.txt 内容减去b.txt内容即为上述内容。

接下来将会介绍文件权限方面的内容,敬请期待。

原文地址:https://www.cnblogs.com/amosli/p/3491670.html