Linux三剑客-sed

  sed 流编辑器(行编辑器,对行进行操作),默认只对缓冲区原始文件得副本编辑,不编辑源文件,sed把当前处理得行存储在临时缓冲区中,称为“模式空间”,sed处理其中得内容,处理后把缓冲区得内容显示,接着处理下一行,直到文件末尾。

-n 显示处理过得行    
    sed -n '2,3p' passwd.txt 只处理文件得2,3行(其中p表示显示行,处理完后打印)

-i    直接修改源文件(一般不推荐)
    
-r    扩展正则表达式

匹配只包含admin的行
    sed -n '/admin/p' passwd.txt

匹配最后一行
    sed -n '$p' passwd.txt

不匹配1,20行
    sed -n '1,20!p' passwd.txt

从匹配admin的行到最后一行
    sed -n '/admin/, $p' passwd.txt

在admin的后面添加username
    sed '/admin/a username' passwd.txt

在admin的前面插入username
    sed '/admin/iusername' passwd.txt

删除第一行
    sed '1d' passwd.txt 

替换匹配到的第一个admin为root
    sed -n 's/admin/root/p' passwd.txt

替换所有的admin为root(g表示全局)
    sed -n 's/admin/root/pg' passwd.txt

替换admin为root后写入到username.txt中
    sed -n 's/admin/root/w username.txt' passwd.txt

将passwd.txt 1-5行写入username.txt
    sed -n '1,5w username.txt' passwd.txt

将passwd.txt 中的字母abc替换成ABC
    sed 'y/abc/ABC/' passwd.txt

将passwd.txt 的admin替换为Admin(1表示()中匹配到的第一组数据)
    sed 's/a(dmin)/A1/g' passwd.txt 

删除文件中行首的空白符
    history | sed 's/^[[:space:]]//g'

获取文件路径的父目录
    pwd | sed 's/^/*//g' | cut -d '/' -f1        

修改grep匹配到的文件中python为python2(其中#类似/表示分隔符,也可以是任何字符)
    sed -i "s#/usr/bin/python#/usr/bin/python2#g" `grep /usr/bin/python -rl /usr/bin/*`
    
原文地址:https://www.cnblogs.com/imlifelong/p/11503630.html