Linux shell脚本攻略(3)-命令使用

1.cat的使用

1.1 cat拼接,拼接多个文件

cat file1 file2 file3 ...

1.2 stdin和另一个文件中的数据组合在一起:

echo 'this is a test ' | cat - file

1.3 去掉多余的空行(1行以上的变为1行空格 )

cat -s file

1.4显示行号

cat -n file

2. find的使用

2.1 根据文件名搜索     -name

find . -name '*.txt' -print #找到所有的 .txt 结尾的文件或目录   

注意*.txt两边的单引号。shell会扩展没有引号或是出现在双引号(")中 的通配符。单引号能够阻止shell扩展*.txt,使得该字符串能够原封不动地传给find命令。

find同时支持逻辑操作符 -o(-or)  -a(-and)操作

find . \(-name '*.txt' -o -name '*.xls' \) -print  #查找出 .txt 或者 .xls结尾的文件或目录

如果想忽略大小写 使用 -iname    比方说 *.txt 和 *. TXT 都可以了

2.2 根据正则表达式搜索     -regex

正则学习:xxxxxx

2.3 否定的使用

$ find . ! -name '*.txt' -print  #排除查找满足项(非)

2.4 查找深度

find 查找的时候会查找所有的子目录。默认情况下,find命令不会跟随符号链接。-L选项可以强制其改变这种行为。但如果碰上了指向自身的链接,find命令就会陷入死循环中。

最大遍历深度:find . -maxdepth 2 -name '*.txt' -print

最小遍历深度:find . -mindepth 2 -name '*.txt' -print

2.5 根据文件类型查找

find . -type d-name '*.txt' -print #目录

find . -type f -name '*.txt' -print #文件

find . -type f -name '*.txt' -print #符号链接

参考:(有些用的不多)

2.6 根据时间搜索

2.6.1:按照天

-atime    #访问时间

 -mtime  #修改内容时间

-ctime  #修改的权限,所有权时间

2.6.2:按照分

-amin   -mmin  -cmin

2.6.2:按照文件大小

-size 


例子:find . -type f -size -100c -print  #小于100字节的文件

2.7:根据find结果操作

1)find . -type f -size -100c -delete #删除小于100字节的文件

2)  find . -type f -size -100c -exec rm -rf {} \;    #删除小于100字节的文件

{} 用来代替find的结果, 结尾必须  \;

2.8find跳过指定目录

例:find . -name '*.git' -prune -o -type f -size -100c -name '*.plist' -print  #跳过 git 目录下的 查找 小于100字节的 .plist 结尾的 文件

3. xargs的使用

1)读取stdin,格式化输出:

cat 1.txt

得到:

1

2

3

4


cat 1.txt | xargs 将会得到 1 2 3     #一行输出的

cat 1.txt | xargs -n 2 将会得到 : #每行2个

1 2

3 4

2)切割 通过  -d

echo 'peter,tom,gordon,hellen,jack,jameson' | xargs -d ,

#按,分开了 结果:peter tom gordon hellen jack jameson

3)结合find使用xargs

find . -mtime -1 -print0 | xargs -0 rm -f  #删除前一天修改的文件

使用find命令的-print0选项生成以空字符('\0')作为分隔符的输出,然后将其作为xargs命令的输入。

4) 统计文件行数

find .  -iname '*.name' -print0 | xargs -0 wc -l

结果:

5)传入其他shell 脚本里

1.sh:####在输入的参数内容后面加入#

#!/bin/bash

echo $@'#'

1.txt:

1

2

3

4

5


命令行来了:

5.1)cat 1.txt | xargs ./1.sh 

输出: 1 2 3 4 5#

5.2)cat 1.txt | xargs -n 2 ./1.sh 

输出:

1 2#

3 4#            

5#

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 5,868评论 2 16
  • 今天去看了烧脑的《记忆大师》。整部影片以家暴为主题展开,以记忆为线索寻找杀人凶手,中间穿插了情感和人性的波动,结局...
    方媛_几里阅读 580评论 2 6
  • 等你 在满池的莲花中等你 在天青色的烟雨中等你 望穿秋天的山和水 等你 从未相遇也无处告别 我的好时光 依旧 春风...
    一江春水1990阅读 604评论 11 15
  • // MPMediaQuery *allMp3 = [[MPMediaQuery alloc] init];...
    wlqsmiling阅读 290评论 0 0