您的位置:首页 > 运维架构 > Shell

shell基础(二)

2015-09-16 23:24 477 查看

1. cat 拼接命令

cat用于拼接多个文件和标准输入

cat file1 file2
输出:
line 1 in file1
line 2 in file1
line 1 in file2
line 2 in file2


echo "hello world" | cat - file.txt
输出 :
hello world
first line in file.txt
second line in file.txt


2.find 查找文件

在目录下查找文件 ,选项:

-name "*.txt"
-iname  "exeample.txt"           忽略大小写
-name "*.txt" -o -name "*.pdf"   其中 -o 相当于或
-path "/home/read*/*.txt"        匹配整个路径,通常需要通配符
! -name "*.txt                   取反
-maxdepth, -mindepth             限定目录深度
-[fldcbsp]                       指定文件类型
-atime      -7                   最后访问时间在7天内
-atime      7                    7天前最后一次访问的文件
-atime      +7                   最后访问时间在7天前的文件
-mtime     [+-]   n              限定最后修改时间
-ctime      [+-]   n             限定元数据的修改时间 ,
包括 权限 文件所有权的修改
-[amc]min  [+-]   n              时间单位是分钟
-size      [+-]  num[cbkMG]      限定文件的大小
-name "*.bak"  -delete           删除匹配的文件
-perm  660                       限定文件权限
-user  userA                     限定文件所有者
-name "*.txt" -exec chmod  777 {} \;
用 -exec对每一个匹配的文件
执行后面的命令


3.xargs 把标准输入转换为参数

cat args.txt
m n
abc
kk


cat args.txt | xargs
m n abc kk


#通过 -n选项可以实现,对参数分批执行 命令
cat args.txt | xargs -n 2
m n
abc kk


#使用-d指定分隔符
echo  "mmpnnpkk" | xargs -d p


cat parm.txt
abc
def A

指定{}为占位符,分别用每行参数填充来执行命令
cat parm.txt  | xargs -I {} printf "%s,%s,%s\n" xx {} yy
xx,abc,yy
xx,def A,yy


find和xargs一起使用,删除bak结尾的文件
find . -name "*.bak" | xargs rm -f


4.tr 从标准输入读取字符,并进行转换

查看进程的环境变量
cat /proc/3928/environ | tr '\0' '\n'
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
XIM_PROGRAM=fcitx
PATH=/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/read_ng/bin
USER=read_ng
...


以集合方式进行映射转换
echo "HELLO WORLD" | tr 'A-z' 'a-z'
hello world


-d选项可以取出特定字符
echo "Hello 12 Wor45ld89" | tr -d '0-9'
Hello  World


-s选项可以去除重复的字符
echo "a b  c d     e" | tr -s  ' '
a b c d e


cat sum.txt
1
2
3
4
cat sum.txt | echo $[ $(tr '\n' '+') 0 ]
10


5.散列函数 md5sum, sha1sum

md5sum text.txt
13d37d878e307450e2116546b66c9a27  text.txt

sha1sum text.txt
803bdc74b3e8c4844f354539431da8ba534d417d  text.txt


6.sort和uniq

sort 对文本排序;
uniq 对已经排序的文本去重


7.expect

expect可以实现自动输入,可以用来测试一些需要输入密码的命令或者脚本;


nameage.sh:

#!/bin/bash
2 echo "enter name:"
3
4 read name
5
6 echo "enter age:"
7
8 read age
9
10 printf "name:%s,age:%s\n"  $name $age


test_expect.sh:

1#!/usr/bin/expect
2 spawn ./nameage.sh
3
4 expect "enter name"
5 send "jame\n"
6
7 expect "age"
8 send "20\n"
9 expect eof


执行test_expect.sh:

[root@wukong shell]# ./test_expext.sh
spawn ./nameage.sh
enter name:
jame
enter age:
20
name:jame,age:20
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: