# -i 忽略查询的大小写 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | grep -i a aAbBcCdDeEfF # -o 只返回匹配规则的值 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | grep -o a a # -v 反向筛选 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | grep -v a gG hH iI jJ kK lL mM nN # 基本正则匹配 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | grep -G [A-Z] aA bB cC dD eE fF gG hH iI jJ kK lL mM nN # 扩展正则匹配 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | grep -E [a-zA-Z]{2} aA bB cC dD eE fF gG hH iI jJ kK lL mM nN
sed
sed 是一个文本替换工具
sed也可以设置规则 替换文件内容
1 2 3 4
[root@iZbp19tqlmjz1dmnm8w43uZ hello]# sed "s/a/A/" hello.txt AA bB cC dD eE fF gG hH iI jJ kK lL mM nN
也可以接收stdout,修改流中的数据
1 2 3 4
[root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed 's/a/A/' AA bB cC dD eE fF gG hH iI jJ kK lL mM nN
# sed 's/old/new/' 只替换每行第一个匹配 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed 's/a/A/' AA bB cC dD eE fF AA hH iI jJ kK lL mM nN # sed 's/old/new/g' 替换每行所有匹配 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed 's/b/B/g' aA BB cC dD eE fF aA hH iI jJ kK lL mM nN BB BBB # sed '2s/old/new/' 只替换第3行的匹配项 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed '3s/b/B/g' aA bB cC dD eE fF aA hH iI jJ kK lL mM nN BB BBB [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed '3s/b/B/' aA bB cC dD eE fF aA hH iI jJ kK lL mM nN BB bbb # sed '2d' 删除第2行 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed '2d' aA bB cC dD eE fF mM nN bB bbb # sed '/^$/d' 删除所有空行 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt aA bB cC dD eE fF
aA hH iI jJ kK lL mM nN bB bbb
[root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed '/^$/d' aA bB cC dD eE fF aA hH iI jJ kK lL mM nN bB bbb # sed -n '5p' 只输出第3行 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed -n 3p aA hH iI jJ kK lL # sed -n '5,10p' 输出第1到3行 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed -n '1,3p' aA bB cC dD eE fF
aA hH iI jJ kK lL # sed '1i\This is a new line' 在第1行前插入 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed '1i\hello' hello aA bB cC dD eE fF
aA hH iI jJ kK lL mM nN bB bbb # sed '1a\This is after line 3' 在第1行后追加 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed '1a\hello' aA bB cC dD eE fF hello
aA hH iI jJ kK lL mM nN bB bbb # sed -e '1d' -e 's/foo/bar/g' 删除第1行并替换所有 aA为 zZ [root@iZbp19tqlmjz1dmnm8w43uZ hello]# cat hello.txt | sed -e '1d' -e 's/aA/zZ/g'
打印第九列 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# ls -l | awk '{print $9}' a ate b c d e f g h hello.txt i j k l m n 打印第一行 [root@iZbp19tqlmjz1dmnm8w43uZ hello]# ls -l | awk 'NR==2{print }' -rw-r--r-- 1 root root 0 Apr 10 13:58 a