Linux 三剑客

grep 过滤

-E  匹配正则表达式 相当于egrep
-o 只输出匹配到的内容
-v 输出不是匹配到的内容
-i 忽略大小写 ,在find中用iname忽略大小写
-n 显示行号
-w 以单词的形式匹配

-A 8 after 同时输出匹配到内容后的8行
-B 9 before 同时输出匹配到内容前的9行
-C 3  同时输出前后3行

-P
-r 递归查找
-l 只显示文件名


注意:
 find /greptest -type f -name "*.cc" |xargs grep "hello"  可以找出这个目录下所有层的内容
 greptest]# grep "hello" /greptest/*.cc 只能在这个目录下查找内容
[root@m01 greptest]# tree /greptest
/greptest
├── 1.cc
├── 2.cc
├── 3.cc
├── 4.cc
├── 5.cc
└── alex
    ├── 1.cc
    ├── 2.cc
    ├── 3.cc
    ├── 4.cc
    └── 5.cc

1 directory, 10 files
[root@m01 greptest]# find /greptest -type f -name "*.cc" |xargs grep "hello"
/greptest/alex/1.cc:hello 127.0.0.1
/greptest/alex/2.cc:hello 127.0.0.1
/greptest/alex/3.cc:hello 127.0.0.1
/greptest/alex/4.cc:hello 127.0.0.1
/greptest/alex/5.cc:hello 127.0.0.1
/greptest/1.cc:hello 127.0.0.1
/greptest/2.cc:hello 127.0.0.1
/greptest/3.cc:hello 127.0.0.1
/greptest/4.cc:hello 127.0.0.1
/greptest/5.cc:hello 127.0.0.1
[root@m01 greptest]# grep "hello" /greptest/*.cc
/greptest/1.cc:hello 127.0.0.1
/greptest/2.cc:hello 127.0.0.1
/greptest/3.cc:hello 127.0.0.1
/greptest/4.cc:hello 127.0.0.1
/greptest/5.cc:hello 127.0.0.1
-r 的用法,不能指定文件类型,加*.cc
[root@m01 greptest]# grep -r "hello" /greptest/
/greptest/alex/1.cc:hello 127.0.0.1
/greptest/alex/2.cc:hello 127.0.0.1
/greptest/alex/3.cc:hello 127.0.0.1
/greptest/alex/4.cc:hello 127.0.0.1
/greptest/alex/5.cc:hello 127.0.0.1
/greptest/1.cc:hello 127.0.0.1
/greptest/2.cc:hello 127.0.0.1
/greptest/3.cc:hello 127.0.0.1
/greptest/4.cc:hello 127.0.0.1
/greptest/5.cc:hello 127.0.0.1

删除空行
egrep -v "^$|^ +$" 1.cc 
优化后:
egrep -v "^ *$" 1.cc>test.cc

sed 过滤 替换 修改文件内容 增删改查

-n 取消默认输出
-i 修改文件内容  -i.bak 修改文件并备份
-r 支持扩展正则
-e 支持多项编辑
用法:
p:输出
a:追加
i:插入
d:删除
sed -n '/hello/p' test.txt
sed -n '/1/,/4/p' test.txt
*sed后置引用*
[root@m01 greptest]# stat /etc/hosts
  文件:"/etc/hosts"
  大小:158        块:8          IO 块:4096   普通文件
设备:fd00h/64768d Inode:16829686    硬链接:1
权限:(0644/-rw-r--r--)  Uid:(    0/    root)   Gid:(    0/    root)
最近访问:2023-03-02 16:40:01.295856421 +0800
最近更改:2013-06-07 22:31:32.000000000 +0800
最近改动:2022-10-07 12:29:29.882369829 +0800
创建时间:-
[root@m01 greptest]# stat -c %a /etc/hosts
644
[root@m01 greptest]# stat -c %A /etc/hosts
-rw-r--r--
方法:
[root@m01 greptest]# stat  /etc/hosts|sed -n '4p'|sed -r 's#^.*\(([0-9]+)/.*#\1#g'
0644
合并后:
[root@m01 greptest]# stat  /etc/hosts|sed -nr '4s#^.*\(([0-9]+)/.*#\1#gp'
0644


awk 过滤 取列 统计计算

awk 参数 '条件{动作}'

参数:
-F 选择分割符号 FS awk内置命令
-v 创建或者修改变量
[root@m01 ~]# x=1
[root@m01 ~]# y=4
[root@m01 ~]# awk -vn1=$x -vn2=$y 'BEGIN{print n1/n2}' #begin:在读取文件之前
0.25

内置变量

NR 行号
RS 记录行结束的标志符
NF 每一行有多少列  $(NF-3)倒数第四列
OFS output FS 输出的分隔符
[root@m01 ~]# awk -F: -vOFS=: '{tmp=$NF;$NF=$1;$1=tmp}1{print $0}' /etc/passwd

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容