shell脚本学识(二)命令字符操作

shell脚本知识(二)命令字符操作

1、cat

不仅可以读取文件并拼接数据,他还能够从标准输入中进行读取。

用cat将输入文件的内容与标准输入拼接在一起:$ echo 'Text through stdin' | cat - file.txt

压缩空白行: 将文本中多个空白行压缩成单个: cat -s file。

移除空白行:cat  file  | tr  -s '\n' 。 将连续多个'\n' 字符压缩成单个'\n' (换行符)。

将制表符显示为^| :cat  -T


2、find

查找中匹配多个条件中的一个,可采用OR条件:

find  /home    \( -name "*.txt"   -o  -name "*.pdf"  \)   匹配txt或者PDF

否定参数 “ ! ”  find /home  ! -name "*.txt"    所有不以txt结尾的文件

find  /home  -type (d 目录、f 普通文件、l 符号链接、 c 字符设备、s 套接字、 p  fifo)

根据文件时间进行修改:-atime(访问时间)  -mtime(修改时间)  -ctime(变化时间),单位是天,

这些数值通常带有 - 或 +:- 表示小于, +表示大于。如:find /home -type f  -atime +7  查找大于7天的文件。

-size 根据文件大小搜索。

删除匹配的文件:find  /home  -type f  -name  "*.swp"  -delete

根据文件权限和所有权匹配:find /home -type f -perm  644 -print  打印出权限位644的文件

-user 匹配用户名


find  /home   -type  f  -user  root  -exec chown  sylnux {} \

{} 是一个特殊的字符串,与-exec结合使用,对于每一个匹配的文件, {}会被替换成相应的文件名。

如:find找到test1.txt 和 test2.txt 则chown sylnux {} 被解释为:chown sylnux test1.txt和chown sylnux test2.txt


3、分割文件和数据

生成一个大小为100kb的测试文件: dd if=/dev/zero  bs=100k count=1 of=data.file

分割成多个小文件:    split  -b 10k data.file   生成10个10k的文件。


4、交互输入自动化

Enter a number:1

Enter name:hello

you have entered 1, hello。

实际上 stdin接收的数据为:“1\nhello\n”。我们按下回车时会发送\n。

所以 echo -e "1\nhello\n"  |  ./interactive.sh 效果是一样的。