Linux 下如何分别打包(压缩)目录下所有文件夹,xargs,awk

这个问题可以通过一行命令完成(当然是通过管道 “|” 所包含多条命令啦)。首先需要拆分这个问题。

  • 获得所有目录列表,通过 grep 命令抓取以 d 标记开头的行,即为目录。
[edwin@edwinW /]# ls
Dropbox  bin  boot  data  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  sbin  selinux  srv  sys  tmp  usr  var  wwwroot
[edwin@edwinW /]# ls -l | grep ^d                   
drwxrwxrwx  6 nobody nobody  4096 Jul 19 05:00 Dropbox
drwxr-xr-x  2 root   root    4096 May 11 19:58 bin
drwxr-xr-x  2 root   root    4096 May 11 19:58 boot
drwxr-xr-x  3 mysql  mysql   4096 Apr 12 19:35 data
drwxr-xr-x 12 root   root   13420 Jul  5 21:45 dev
drwxr-xr-x 53 root   root    4096 Jul 12 20:38 etc
drwxr-xr-x  6 root   root    4096 May 11 19:58 home
drwxr-xr-x  9 root   root    4096 Jul  1 00:02 lib
drwxr-xr-x  7 root   root    4096 Jul  1 00:01 lib64
drwx------  2 root   root   16384 May 18  2010 lost+found
drwxr-xr-x  2 root   root    4096 May 11 19:58 media
drwxr-xr-x  3 root   root    4096 Jun 12 21:32 mnt
drwxr-xr-x  2 root   root    4096 May 11 19:58 opt
dr-xr-xr-x 96 root   root       0 Jul  5 21:45 proc
drwxr-x---  8 root   root    4096 Jul 12 20:07 root
drwxr-xr-x  2 root   root    4096 Jul  1 00:02 sbin
drwxr-xr-x  2 root   root    4096 May 11 19:58 selinux
drwxr-xr-x  2 root   root    4096 May 11 19:58 srv
drwxr-xr-x 13 root   root       0 Jul  5 21:45 sys
drwxrwxrwt  6 root   root   94208 Jul 19 23:39 tmp
drwxr-xr-x 15 root   root    4096 Jun 12 21:24 usr
drwxr-xr-x 18 root   root    4096 Jun 12 21:24 var
  • 这样只是 ls 了所有目录,接下来需要获得目录下所有文件夹名称,不需要多余信息。使用 awk 选取名称列。
[edwin@edwinW /]# ls -l | grep ^d | awk '{print $9}'
Dropbox
bin
boot
data
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
sbin
selinux
srv
sys
tmp
usr
var
  • 接下来最后一步是打包这些目录。使用 xargs 来实现。
[edwin@edwinW /]# ls -l | grep ^d | awk '{print $9}' | xargs -i tar jcvf {}.tbz {}

 

其实 Linux 下很多问题都可以这样一步一步分解成不同部分,用不同命令组合来完成,这就是 bash 脚本的精髓。

 

参考:

awk:http://linux.die.net/man/1/awkhttp://www.gnu.org/software/gawk/manual/gawk.html

xargs:http://unixhelp.ed.ac.uk/CGI/man-cgi?xargshttp://en.wikipedia.org/wiki/Xargs

cut:http://www.manpagez.com/man/1/cut/

grep:http://unixhelp.ed.ac.uk/CGI/man-cgi?grep


Comments

2 responses to “Linux 下如何分别打包(压缩)目录下所有文件夹,xargs,awk”

  1. find . -maxdepth 1 -type d

    1. yeah,学到一招,谢啦。Linux 处理的方法各种各样,这也是喜欢 Linux 的原因。

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.