tar命令的实用详解(C参数和排除文件 --exclude)

一、tar:从压缩包中解压出指定文件

[root@d176 test]# tar ztf nrpe-2.12.tar.gz |grep src
nrpe-2.12/src/
nrpe-2.12/src/.cvsignore
nrpe-2.12/src/Makefile.in
nrpe-2.12/src/check_nrpe.c
nrpe-2.12/src/nrpe.c
nrpe-2.12/src/snprintf.c
nrpe-2.12/src/utils.c
[root@d176 test]# tar zxvf nrpe-2.12.tar.gz nrpe-2.12/src        //解压
nrpe-2.12/src/
nrpe-2.12/src/.cvsignore
nrpe-2.12/src/Makefile.in
nrpe-2.12/src/check_nrpe.c
nrpe-2.12/src/nrpe.c
nrpe-2.12/src/snprintf.c
nrpe-2.12/src/utils.c
[root@d176 test]# ls
bijiao httpd.conf.bak_2015-07-12 locl nrpe-2.12 nrpe-2.12.tar.gz server.xml txt
[root@d176 test]# ls nrpe-2.12
src
[root@d176 test]# ls nrpe-2.12/src/
check_nrpe.c Makefile.in nrpe.c snprintf.c utils.c

[root@d176 test]# tar zxvf nrpe-2.12.tar.gz nrpe-2.12/src -C /root/hhhhhhhhhh/         //指定-C参数不行
nrpe-2.12/src/
nrpe-2.12/src/.cvsignore
nrpe-2.12/src/Makefile.in
nrpe-2.12/src/check_nrpe.c
nrpe-2.12/src/nrpe.c
nrpe-2.12/src/snprintf.c
nrpe-2.12/src/utils.c

或另外一种方式=============>

[root@d176 hhhhhhhhhh]# tar  zxvf  /root/test/nrpe-2.12.tar.gz nrpe-2.12/src          //进入到要解压的目标目录
nrpe-2.12/src/
nrpe-2.12/src/.cvsignore
nrpe-2.12/src/Makefile.in
nrpe-2.12/src/check_nrpe.c
nrpe-2.12/src/nrpe.c
nrpe-2.12/src/snprintf.c
nrpe-2.12/src/utils.c
[root@d176 hhhhhhhhhh]# ls
nrpe-2.12
[root@d176 hhhhhhhhhh]# ls nrpe-2.12/
src
[root@d176 hhhhhhhhhh]# ls nrpe-2.12/src/
check_nrpe.c Makefile.in nrpe.c snprintf.c utils.c

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

二、tar:-C参数.

也可以排除目录与文件一起混合使用,如:

[root@lee ~]# tar -cvf test.tgz test/ --exclude dir1 --exclude a.log --exclude *.jpg
test/
test/b.txt
test/dir2/
test/b.log
test/a.txt

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

三、tar:压缩解压排除指定文件/目录/文件类型等.

问题:在/home/usr1目录下,想要打包/home/usr2目录中的文件file2,应该使用什么样的tar命令?

解答1:
$ tar -cvf file2.tar /home/usr2/file2
tar: Removing leading '/' from members names
home/usr2/file2
该命令可以将/home/usr2/file2文件打包到当前目录下的file2.tar中,需要注意的是:使用绝对路径标识的源文件,在用tar命令压缩后,文件名连同绝对路径(这里是home/usr2/,根目录'/'被自动去掉了)一并被压缩进来。使用tar命令解压缩后会出现以下情况:
$ tar -xvf file2.tar
$ ls
…… …… home …… …… 
解压缩后的文件名不是想象中的file2,而是home/usr2/file2。

解答2:
$ tar -cvf file2.tar -C /home/usr2 file2
该命令中的-C dir参数,将tar的工作目录从当前目录改为/home/usr2,将file2文件(不带绝对路径)压缩到file2.tar中。注意:-C dir参数的作用在于改变工作目录,其有效期为该命令中下一次-C dir参数之前。
使用tar的-C dir参数,同样可以做到在当前目录/home/usr1下将文件解压缩到其他目录,例如:
$ tar -xvf file2.tar -C /home/usr2
而tar不用-C dir参数时是无法做到的:
$ tar -xvf file2.tar /home/usr2
tar: /tmp/file: Not found in archive
tar: Error exit delayed from previous errors

原文地址:https://www.cnblogs.com/itcomputer/p/4664574.html