再来一些shell技巧

1. 批量删除某些指定文件

我们都知道用find,很快就可以给出:

find . -name ‘your_pattern*’ -exec rm -f {} ;

恩,不过还有更快更简洁的方法,用find自带的delete:

find . -name ‘your_pattern*’ -delete

2. 列出当前目录下的所有目录(不递归)

你能想到几种方法?我这里有三种解决方法:

(1) $ ls -l | egrep ‘^d’

(2) $ find . -maxdepth 1 -type d

(3) $ ls -d */.

最后一个是从别处看来的,很巧妙。欢迎提供其它不同的方法。

3. 打印文件的倒数第N行

以倒数第2行为例,我的通常做法是:

$ tail -2 my_file | head -1

另一种方法是:

$ gawk ‘BEGIN {RS = “none_existed_pattern”; FS = “n”}; END {print $(NF-2)}’ my_file

[注:在一些awk(不是gawk)中,RS应该是一个字符,而不能是正则表达式。]

4. 产生连续的数字

常见的方法是用seq:

比如产生1~10的数字,

$ seq 1 10

其实也可以用:

$ echo {1..10}

倒叙时这样:

$ seq 10 -1 1

或者:

$ echo {10..1}

用seq的好处是可以指定步长,但它只能针对数字; {..}虽然不能指定步长,但可以适用于字母。另外,很明显,seq的分隔符是n,而{..}是空格。

5. *grep

你最常用的很可能是grep,可是除此还有两个grep:fgrep和egrep。fgrep是Fixed grep的缩写,而不是fast grep,事实上,搜索同样的字符串时fgrep通常比grep要慢;egrep是Extended grep的所写,因为它采用了扩展的正则表达式和更好的算法,所以你应该更倾向于用egrep而不是grep。

题外话:有多少人知道grep是什么缩写?我也是最近才知道的,它其实是Global Regular Expression Print的缩写,ms也有人说是Get Regular Expression And Print。grep如此常用,以至于连词典都把它收录为一个单词了。

[Jargon File]
grep

/grep/ vi. [from the qed/ed editor idiom g/re/p, where re stands for a regular expression, to Globally search for the Regular Expression and Print the lines containing matches to it, via Unix grep(1)'] To rapidly scan a file or set of files looking for a particular string or pattern (when browsing through a large set of files, one may speak ofgrepping around’). By extension, to look for something by pattern. “Grep the bulletin board for the system backup schedule, would you?” See also vgrep.