zoukankan      html  css  js  c++  java
  • Shell脚本之sed的使用

    1.sed命令;主要作用是查找;新增 删除 和修改替换。

    user.txt 

    daokr#cat user.txt
    ID    Name    Sex    Age
    1    zhang    M    19
    2    wang    G    20
    3    cheng    M    10
    4    huahua    M    100

    查找命令:-n 和 p(print)

    在user.txt文件中;匹配带h的行 并且只显示1,3行

    cat user.txt | grep h |sed -n '1,3p'

    daokr#cat user.txt | grep h |sed -n '1,3p'
    1    zhang    M    19
    3    cheng    M    10
    4    huahua    M    100

    删除命令:d(delete)

    删除最后一行记录

       cat user.txt | grep h | sed '$d'

    在user.txt中显示带h的行;并且从结果中删掉2,3行的记录;只看第一行记录

    cat user.txt | grep h |sed '2,3d'
    daokr#cat user.txt | grep h
    1    zhang    M    19
    3    cheng    M    10
    4    huahua    M    100
    daokr#cat user.txt | grep h |sed '2,3d'
    1    zhang    M    19

    新增数据:a (append)

    在user.txt中查询出带h的行;并在第二行后面添加新的一行数据

    cat user.txt | grep h |sed '2a5 huang G 40'

    前面插入:i (insert)

    在第二行插入2行数据的签名插入新增的数据:

    cat user.txt | grep h |sed '2i hello word'

    数据行替换:c

    把第二行数据;用命令c替换成 10  wanghua  N  90

    cat user.txt | grep h |sed '2c 10 wanghua N 90'

    字符串的替换:s 

    格式为“行范围s/旧字串/新字串/g”

    daokr#cat user.txt | grep h
    1    zhang    M    19
    3    cheng    M    10
    4    huahua    M    100
    daokr#cat user.txt | grep h |sed '2s/ch/wh/g'
    1    zhang    M    19
    3    wheng    M    10
    4    huahua    M    100

    替换并写入文件:-i

    把第3行的数据里的wang 替换成heee 并写入到user.txt

    sed -i '3s/wang/heee/g' user.txt

    daokr#sed -i '3s/wang/heee/g' user.txt
    daokr#cat user.txt 
    ID    Name    Sex    Age
    1    Fhang    M    19
    2    heee    G    20
    3    cheng    M    10
    4    huahua    M    100

    多行替换:-e

    sed -e 's/zhang//g ; s/wang//g' user.txt    # -e允许多条命令顺序执行,用分号隔开,s前面不加数字表示所有行

    sed -e 's/he/wl/g;s/hua/lua/g' user.txt

    daokr#sed -e 's/he/wl/g;s/hua/lua/g' user.txt
    ID    Name    Sex    Age
    1    Fhang    M    19
    2    wlee    G    20
    3    cwlng    M    10
    4    lualua    M    100
  • 相关阅读:
    autoMapper dotnetcore webapi 自动添加映射 abp
    win10安装MongoDB提示 the domain,user name and/or password are incorrect. Remember to use "." for the domain if the account is on the local machine.
    webapi 重复提交问题
    webapi postman 415 错误
    sqlserver 更新通过 select 查询出的结果集
    2016-03至2016-08前端工作总结
    css笔记——css 实现自定义按钮
    javascript笔记——date以及datetime的比较
    node.js笔记——gulp
    javascript笔记——密码组合规则
  • 原文地址:https://www.cnblogs.com/wanglijun/p/8716265.html
Copyright © 2011-2022 走看看