记录Linux常用shell命令:cat、find、xargs、split等。

二、常用命令

2.1.cat

通过cat命令对多个文件进行拼接输出

cat  file1 file2 file3...
#常用参数
cat -n 打印行号
cat -s 压缩空白行,将多个空白行压缩为单个
cat -t 将制表符重点标记出来 标记为 ^I
cat file1.txt|tr -s "\n" 使用tr移除空白行。

2.2.find

沿着文件层次结构向下遍历,匹配符合条件的文件。

#-print  打印出匹配的文件和路径以'\n'为界定符
#-print0 以'\0' 为界定符
find . -print
find . -name "*.go" -print
#-iname   忽略大小写
find . -iname "*.go" -print
#-o 匹配多个条件采用or操作
find . \(-name "*.go" -o -name "*.html"\) -print
# -path 通配符匹配文件和路径
find . -path "*controllers*" -print
# -regex  基于正则匹配路径
#  !否定参数
find . ! -name "*.go" -print

#-maxdepth -mindepth  基于目录深度的搜索
#根据文件类型搜索  -type
# 普通文件 f
# 符号文件 l
# 目录    d
# 字符设备 c
# 块设备   b
# 套接字   s
# Fifo    p
find . -type f -print
#根据文件时间进行搜索 
#天 atime 访问时间#mtime 修改时间#ctime文件元数据改变时间
#分钟 amin mmin cmin
#搜索修改时间7天的文件
find . -type f -mtime +7 -print 
#-newer 指定一个参考文件,找出比参考文件修改时间更长的文件
find . -type f -newer file.txt -print 
#基于文件大小的搜索
#文件大小单元
	b 块(512字节)
	c 字节
	w 字(2字节)
	k
	M
	G
大于2k的文件
find . -type f -size +2k
#删除匹配文件
find . -type f -name “*.swap” -delete
#基于文件权限和使用权的匹配
find . -type f -name “*.go” -perm 644 -print
find . -type f -name “*.go” -perm 644 -print
find . -type f -name “*.go” -user root -print
#组合使用-exec
find . -type f -name “*.go” -user root -exex chown www {} \;		

2.3.xargs

把从stdin接收的数据重新格式化 在作为参数提供给其他命令使用。

find . -name "*.css" -print |xargs
find . -name "*.css" -print |xargs -n 2 
#-d 指定限定符 但是mac没有-d参数                                        
echo "a;b;c;d;e;f;g"|xargs -d ";"
#结合find使用 删除匹配文件
find . -name "*.css" -print0|xargs -0 rm -rf
#统计go代码行数
find . -name "*.go" -print0|xargs -0 wc -l 

2.4.tr

进行字符串替换 删除和压缩

echo  “HELLO” | tr "A-Z" "a-z"
替换制表符为空格
cat file.txt|tr '\t' ''
删除数组并打印
echo "hello 123 world 456"|tr -d '0-9'
删除除数字之外的其他 
echo "hello 123 world 456"|tr -d -c '0-9' 

2.5.md5sum

校验

md5sum t.txt

2.6.排序、单一与重复

  • sort
cat t.txt|sort
#排序根据数字
cat t.txt|sort -n
#逆序排序
cat t.txt|sort -r
根据月份进行排序
cat t.txt|sort -M
#-k 指定根据哪个key进行排序 
#根据第一列逆向排序
cat t.txt|sort -nrk 1
#-b 忽略文件中的前导空白字符 -d 指明以字典序进行排序
cat t.txt|sort -bd 
  • uniq
#过滤重复的行
cat t.txt|uniq 
#统计各行在文件中出现的次数
cat t.txt|uniq -c
#-s指定跳过前N个字符 -w 指定用于比较最大字符数
cat t.txt
输出:
u:01:unix
d:04:linux
u:01:freebsd
u:01:centos    
cat t.txt|uniq -s 2 -w 2
输出:
d:04:linux
u:01:freebsd 

2.7.分割文件和数据

构建测试数据
dd if=/dev/zero bs=10k count=10 of=data.file
# 拆分100个文件  k(kb) M(MB) G(GBg) c(byte 1B) w(word 2B) b(块 512B)
split -b 10k data.file
-d 指定为字母后缀 -a 指定后缀的长度
split -b 10k  -d -a 4 data.file
#split最后一个参数为 PREFIX 用来指定前缀
split -b 1024k  -d -a 4 data.file split_file_
#-l指定行数进行文件分割 eq:指定10行
split -l 10 data.file