linux shell几个小demo

来源:互联网 发布:淘宝女童秋季外套新款 编辑:程序博客网 时间:2024/06/08 11:14

闲来无事,写几个shell script来练练手,发现我的mac下的shell和ubuntu下的shell有些语法还是有区别,网上的一些教程,在我的mac上并不适用,需要修改。

1、编写shell脚本,将/users/sunwangdong/desktop/wordcount下的大于10000k的文件信息输出

我写了一个名字为test.sh的脚本,如下所示:

#!/bin/bashfor FILE in `ls /users/sunwangdong/desktop/wordcount/`do#echo $FILEif [ -f "/users/sunwangdong/desktop/wordcount/$FILE" ]then#echo $FILEif [ `ls -al /users/sunwangdong/desktop/wordcount/$FILE | awk '{print $5}'` -lt 10000 ]thenls -al /users/sunwangdong/desktop/wordcount/$FILE | awk '{print $0}'fifidone
其中,第一行的for循环中,内部需要用反斜号`来表示,在第二个if语句中,首先要用ls将显示的文件通过管道发给awk,然后由awk来输出第5列的内容,然后再判断其值是否大于10000k,那么这里在和10000k比较之前,需要用反斜号阔住。结果如下:

-rw-r--r--@ 1 sunwangdong  staff  6148  3  3 23:46 /users/sunwangdong/desktop/wordcount/.DS_Store-rw-r--r--  1 sunwangdong  staff  1916  2 26 21:43 /users/sunwangdong/desktop/wordcount/pom.xml-rw-r--r--  1 sunwangdong  staff  9789  2 26 21:29 /users/sunwangdong/desktop/wordcount/wordcount.iml
2、一个有序文件:file_sort
内容是:
1
2
3
4
5
6

要对其进行切分成3个文件 file.1 file.2 file.3
要求:第n行内容 < 任意文件的n+1行内容
如:
file.1  
1
4
file.2
2
5
file.3
3
6
#!/bin/bashi=1while(($i<=6))do    int=$((i%3))    if [ $int -eq 0 ]    then        int=$((int+3))    fi    awk -v num=$i 'NR==num {print}' file_sort >> file.$int    i=$((i+1))    done
很简单易懂的方法实现,注意在if语句中,中括号前有一个空格,shell特别注重这些空格。